需求:
根据类自行new出的对象中,使用spring管理的对象
所需工具:
工具类:ApplicationContextUtil.class
注入类:SupplierServiceImpl.class,SupplierService.class
测试类:BeanTest.class
代码:
工具类:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Component
@Lazy(false)
public class ApplicationContextUtil implements ApplicationContextAware {
protected static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(String name) {
//name表示其他要注入的注解name名
return (T) context.getBean(name);
}
public static <T> T getBean(Class<T> requiredType) {
return context.getBean(requiredType);
}
}
解释:当一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得ApplicationContext中的所有bean。换句话说,就是这个类可以直接获取spring配置文件中,所有有引用到的bean对象。
注入类:
@Service("suppServImp")
public class SupplierServiceImpl implements SupplierService {
public void test(){
System.out.println("print test data");
}
}
public interface SupplierService {
public void test();
}
测试类:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PlantformApplication.class)
public class BeanTest {
private static SupplierService supplierService ;
@Test
public void test1(){
supplierService = ApplicationContextUtil.getBean("suppServImp");
SupplierService supplierService = (SupplierService) getBean();
supplierService.test();
}
private static Object getBean(){
return supplierService;
}
}
测试输出:
print test data
总结:
- 工具类上一定要写@Component注解,不然无法注入