Java项目启动时执行指定方法的2种方式

痛定思痛。 2024-03-26 15:45 146阅读 0赞

以上两种都是项目启动的时候就会执行的类

1、实现 ApplicationRunner 接口

  1. @Component
  2. @Order(value = 1)//此注解的作用就是控制类的加载顺序,这个顺序是从小到大的。比如说启动时先去加载Order的value等于1的类,然后去加载等于2的类。
  3. public class MyApplicationRunner implements ApplicationRunner{
  4. @Override
  5. public void run(ApplicationArguments args) throws Exception{
  6. //项目启动时需要执行的代码
  7. }
  8. }

2、@Configuration注解的配置类

  1. @Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的
  2. 方法,这些方法将会被AnnotationConfigApplicationContextAnnotationConfigWebApplicationContext
  3. 类进行扫描,并用于构建bean定义,初始化Spring容器。
  4. @Configuration启动容器+@Bean注册Bean@Bean标注在方法上(返回某个实例的方法),等价于spring
  5. xml配置文件中的<bean>,作用为:注册bean对象。
  6. 代码实例:
  7. @Configuration
  8. public class KaptchaConfig {
  9. @Bean
  10. DefaultKaptcha producer() {
  11. Properties properties = new Properties();
  12. properties.put("kaptcha.border", "no");
  13. properties.put("kaptcha.textproducer.font.color", "black");
  14. properties.put("kaptcha.textproducer.char.space", "4");
  15. properties.put("kaptcha.image.height", "40");
  16. properties.put("kaptcha.image.width", "120");
  17. properties.put("kaptcha.textproducer.font.size", "30");
  18. Config config = new Config(properties);
  19. DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
  20. defaultKaptcha.setConfig(config);
  21. return defaultKaptcha;
  22. }
  23. }

发表评论

表情:
评论列表 (有 0 条评论,146人围观)

还没有评论,来说两句吧...

相关阅读