从springBoot中的不同类调用方法

时间:2019-04-11 10:09:40

标签: java spring

我想调用一个包含applicationContext的方法,该方法在独立运行时可以正常工作,但是当我尝试从其他类appContext.getBean(DataSource.class)调用它时将返回null。

public class Action {

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

@Autowired
MessageConfigProperties messageProperties;

@Autowired
AutomatorApp automatorApp;

@Autowired
Apps gapps;

@Autowired
Deploy d;

@Autowired
Deploy depstatusChk;

@Autowired
private ApplicationContext appContext;

@Autowired
CreateSaltFileService createSaltFile;

@Autowired
DeployFactory depFactory;

@Autowired
IMoveAppsService moveAppsService;

@Autowired
IUserEnvironmentService userEnvService;

@Autowired
IEnvironmentService envService;

@Autowired
Session session;

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

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

@POST
@Path("/register/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RequiresRoles("admin")
@RequiresPermissions("automator:register")
public Session register(Session credentials, @BeanParam Session springContext) throws AppException {
    System.out.println("into action class");
    System.out.println("-->>>" +appContext.getBean(DataSource.class));
    appContext.getBean(DataSource.class);
    logger.info(messageProperties.getGreetings());
    // logger.trace("Inside Session");
    System.out.println("Inside Session");
    credentials.setDatasource(springContext.getDatasource());

从以下位置调用此Action方法时

此方法agentGroup在不同的类中

@POST
@Produces(MediaType.APPLICATION_JSON)
@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 个答案:

答案 0 :(得分:1)

@Autowire ApplicationContext appContext只是为了获取数据源(appContext.getBean(DataSource.class))。

为什么不直接@Autowire DataSource datasource? 它将使Action类的业务逻辑独立于Spring。

如果您确实要访问ApplicationContext,则可以尝试另一种方法

制作Action implements ApplicationContextAware

私有ApplicationContext ctx;

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

有关详细信息,请参见Circular dependency in Spring

编辑: 您的Action类没有注释。否org.springframework.web.bind.annotation. RestController,否@Component@Service。您确定它是由Spring管理的吗?如果只是使用new创建的,则自动装配将不起作用,并且字段将为空。