Spring boot添加配置类@Configuration并初始化@Bean,@Resource和@Autowired都为null
大写加黑,找了好久@Resource和@Autowired都依赖不到创建的bean的原因:@Bean的方法名即是创建的Bean名称
import org.activiti.engine.ProcessEngines; import org.activiti.engine.RepositoryService; import org.activiti.engine.TaskService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ActivitiConfig { @Bean public RepositoryService repositoryService() { System.out.println("初始化RepositoryService"); RepositoryService repositoryService = ProcessEngines.getDefaultProcessEngine().getRepositoryService(); System.out.println(repositoryService); return repositoryService; } @Bean public TaskService taskService() { System.out.println("初始化TaskService"); TaskService taskService = ProcessEngines.getDefaultProcessEngine().getTaskService(); System.out.println(taskService); return taskService; } }
测试类:
import org.activiti.engine.RepositoryService; import org.activiti.engine.TaskService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; @SpringBootTest @RunWith(SpringRunner.class) public class DemoApplicationTests { @Autowired private RepositoryService repositoryService; @Resource private TaskService taskService; @Test public void getProcessEngine() { System.out.println("获取RepositoryService:" + repositoryService); System.out.println("获取TaskService:" + taskService); } }
结果: