SpringBoot XML和JavaConfig

0 前言

0.1 为什么需要使用SprintBoot

spring和SpringMVC需要使用大量的配置文件。需要配置各种对象,把对象放到spring容器中才能使用对象。

SpringBoot相当于不需要配置文件的Spring和SpringMVC。常用的框架和第三方库都已经配置好了,可以直接使用。提高了开发效率。

1 JavaConfig

JavaConfig是Spring提供的使用java类配置容器。配置Spring IOC容器的纯java方法。
【优点】
(1) 可以使用面向对象方式,一个配置类可以继承配置类,可以重写方法
(2) 避免了繁琐的xml配置。

1.1 注解

@Configuration: 放在类上面,表示这个类可以作为配置文件使用。
@Bean:声明对象,把对象注入到容器中。此注解,如果不指定兑现的名称,默认方法名称就是id。使用name属性指定bean的id

@Configuration
public class SprintConfig {
    
    
    /**
     *  方法返回值的对象就直接被注入到容器中了。
     */
	@Bean
	public Student createStudent() {
    
    
		Student student = new Student();
		student.setName();
		student.setAge();
		student.setSex();
		return student;
	}
}

2 @ImportResource

注解的作用是导入其他的xml配置文件。等同于xml文件的resources标签

<import resources = "其他配置文件">
@Configuration
@ImportResource(value = "classpath:applicationContext.xml")
public class SprintConfig {
    
    
}

3 @PropertyResource

读取properties属性配置文件,使用属性配置文件可以实现外部化配置,在程序之外提供数据。

tiger.name= dongbeihu
tiger.age=12
@Component("tiger")
public class Tiger {
    
    
	@Value(${
    
    tiger.name})
	private String name;
	@Value(${
    
    tiger.age})
	private int age;
}
@Configuration
@ImportResource(value = "classpath:applicationContext.xml")
@PropertySource(value = "classpath:config.properties")
@ComponentScan(basePackages = "com.xxx.vo")
public class SprintConfig {
    
    
}

猜你喜欢

转载自blog.csdn.net/kaikai_sk/article/details/126409423