springboot启动执行
说明:有个需要启动就执行的方法,但是有注入springboot的实例。springboot通过@Autowired注入的bean实例,如果对被注入的对象通过new的方式获取实例,就会出现@Autowired注入的实例为null的情况。所以这里不能用main方法来完成启动执行任务
springboot的注释解释
-
@Autowired 自动导入对象到类中,被注入进的类同样要被 Spring 容器管理比如:Service 类注入到 Controller 类中。
-
@Component 通用的注解,可标注任意类为 Spring 组件。如果一个 Bean 不知道属于哪个层,可以使用@Component 注解标注。
-
@PostConstruct 要在依赖加载后,对象使用前执行,而且只执行一次。所有支持依赖注入的类都要支持此方法。 文档中说一个类只能有一个方法加此注解,但实际测试中,我在一个类中多个方法加了此注解,并没有报错,而且都执行了,我用的是 Spring Boot 框架。
在一个bean的初始化过程中,方法执行先后顺序为先执行完构造方法,再注入依赖,最后执行初始化操作,所以这个注解就避免了一些需要在构造方法里使用依赖组件的尴尬。
Constructor > @Autowired > @PostConstruct
- 示例代码
@Component
public class StartSub {
private String channel = "mytest";
Logger logger = Logger.getGlobal();
@Autowired
JedisPool jedisPool;
@PostConstruct
public void startSub() {
Subscriber subscriber = new Subscriber();
Jedis subscriberJedis = jedisPool.getResource();
new Thread() {
public void run() {
subscriberJedis.subscribe(subscriber, channel);
}
}.start();
}
}
此段代码注入的了一个jedispool的对象,启动订阅redis频道。