2 ways to execute specified methods when starting a Java project

The above two are classes that will be executed when the project is started :

1. Implement the ApplicationRunner interface

@Component
@Order(value = 1)//此注解的作用就是控制类的加载顺序,这个顺序是从小到大的。比如说启动时先去加载Order的value等于1的类,然后去加载等于2的类。
public class MyApplicationRunner implements ApplicationRunner{

    @Override
    public void run(ApplicationArguments args) throws Exception{
        //项目启动时需要执行的代码
        
    }
}

2. Configuration class annotated with @Configuration

     @Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的
方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext
类进行扫描,并用于构建bean定义,初始化Spring容器。
     @Configuration启动容器+@Bean注册Bean,@Bean标注在方法上(返回某个实例的方法),等价于spring
的xml配置文件中的<bean>,作用为:注册bean对象。

代码实例:

@Configuration
public class KaptchaConfig {

	@Bean
	DefaultKaptcha producer() {
		Properties properties = new Properties();
		properties.put("kaptcha.border", "no");
		properties.put("kaptcha.textproducer.font.color", "black");
		properties.put("kaptcha.textproducer.char.space", "4");
		properties.put("kaptcha.image.height", "40");
		properties.put("kaptcha.image.width", "120");
		properties.put("kaptcha.textproducer.font.size", "30");

		Config config = new Config(properties);
		DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
		defaultKaptcha.setConfig(config);

		return defaultKaptcha;
	}

}

Guess you like

Origin blog.csdn.net/Little_Arya/article/details/129269592