使用到的注解@Component、@Autowried、@PostConstruct
一、类头部需要添加@Component ,把当前类注册成一个bean
二、在需要注入的类引入Autowired
三、使用@PostConstruct注解执行类所需的初始化操作
四、在别的类使用这个类的时候不能用new,只能用注入的方式
如下实例:
@Component public class UtilAutoInTest { @Autowired private HsCollegeServiceI hsCollegeServiceI; public static UtilAutoInTest autoInTest; @PostConstruct public void init(){ autoInTest = this; } public static void test(){ List<InfoCollege> colleges = autoInTest.hsCollegeServiceI.combobox(); } public void test2(){ List<InfoCollege> colleges = hsCollegeServiceI.combobox(); } } 执行顺序:先执行构造方法,再注入依赖,最后执行初始化操作 即Constructor > @Autowired > @PostConstruct
其他类调用该类的方法 :
@Controller public class UserConstroller{ @Autowired private UtilAutoInTest autoInTest; @GetMapping("/user") public void test(){ autoInTest.test(); autoInTest.test2(); } }
@PostConstruct 修饰一个非静态的void()方法
@PostConstruct public void someMethod(){} 或者 public @PostConstruct void someMethod(){}
要将对象p注入到对象a,那么首先就必须得生成对象a和对象p,才能执行注入。所以,如果一个类A中有个成员变量p被@Autowried注解,那么@Autowired注入是发生在A的构造方法执行完之后的。
如果想在生成对象时完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入,那么久无法在构造函数中实现。为此,可以使用@PostConstruct注解一个方法来完成初始化,@PostConstruct注解的方法将会在依赖注入完成后被自动调用。
Constructor >> @Autowired >> @PostConstruct