线程中无法直接使用注解的方式获取spring beans,但是线程经常需要用到bean来实现业务流程;这里有两种方式
方法1:是通过初始化线程实现类的方式通过set私有属性,把bean赋值到线程实现类中;
方法2:通过applicationcontext线程中直接获取bean;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; 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 com.polymer.app.StartApplication; import com.polymer.app.service.MockService; import com.polymer.app.utils.ApplicationContextHandle; @RunWith(SpringRunner.class) @SpringBootTest(classes = StartApplication.class) public class TestThreadAOP { private static ExecutorService excutor = Executors.newFixedThreadPool(1); @Autowired private MockService mockService; @Test public void testTAOP() throws InterruptedException, ExecutionException { Task t = new Task(); t.setName("zhangyf"); t.setMockService(mockService); excutor.execute(t); } class Task implements Runnable { private String name; private MockService mockService; public MockService getMockService() { return mockService; } public void setMockService(MockService mockService) { this.mockService = mockService; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public void run() { //方式一 /*String call = mockService.call(); System.out.println(call + name);*/ //方式二 System.out.println("获取springbeans开始---"); MockService mock = (MockService) ApplicationContextHandle.getBean("mockSeviceImpl"); System.out.println("获取springbeans结束---"); String call = mock.call(); System.out.println(call + name); } } }
import org.apache.log4j.Logger; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Configuration; @Configuration//springboot的使用applicationcontext必须要使用此注解,否则不生效 public class ApplicationContextHandle implements ApplicationContextAware { private static ApplicationContext applicationContext; private final static Logger logger = Logger.getLogger(ApplicationContextHandle.class); @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ApplicationContextHandle.applicationContext = applicationContext; } /** * 获取对象 * 这里重写了bean方法,起主要作用 * @param name * @return Object 一个以所给名字注册的bean的实例 * @throws BeansException */ public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); } }
以往的spring则是需要手动添加<bean id="ApplicationContextHandle" class="com.polymer.app.utils.ApplicationContextHandle"/>