i want to call a method which is containing applicationContext which works fine when run independently but when i try calling it from a different class appContext.getBean(DataSource.class) returns null.

public class Action {

private static Logger log = LoggerFactory.getLogger(Action.class);

MessageConfigProperties messageProperties;

AutomatorApp automatorApp;

Apps gapps;

Deploy d;

Deploy depstatusChk;

private ApplicationContext appContext;

CreateSaltFileService createSaltFile;

DeployFactory depFactory;

IMoveAppsService moveAppsService;

IUserEnvironmentService userEnvService;

IEnvironmentService envService;

Session session;

private Logger logger = LoggerFactory.getLogger(Action.class);
private ServletContext context;

public void setServletContext(ServletContext context) {
    System.out.println("servlet context set here");
    this.context = context;

public Session register(Session credentials, @BeanParam Session springContext) throws AppException {
    System.out.println("into action class");
    System.out.println("-->>>" +appContext.getBean(DataSource.class));
    // logger.trace("Inside Session");
    System.out.println("Inside Session");

when this Action method is called from

this method agentGroup in different class

@ApiOperation(value = "Get List of agent group", response = 
AgentGroup.class, responseContainer = "List")
public ArrayList<AgentGroup> agentGroup(Session credentials, @BeanParam Session springContext) throws AppException, ConfigException, InterruptedException {

    Session r=objA.register(credentials, springContext);
    int sessionId=r.getSessionId();

1 Answers

Bartosz Bilicki On

You @Autowire ApplicationContext appContext just to get datasource (appContext.getBean(DataSource.class)).

Why do not @Autowire DataSource datasource directly? It will make make business logic of your Action class independend from Spring.

If you really want to access ApplicationContext you may try another approach

make Action implements ApplicationContextAware

private ApplicationContext ctx;

    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        ctx = applicationContext;

See Circular dependency in Spring for details.

edit: your Action class has no annotation. no org.springframework.web.bind.annotation. RestController, no @Component or @Service. are you sure it is managed by Spring? if it is just created using new then Autowire will not work and fields will be null.