@PropertySource carga el archivo de configuración especificado
application.properties o application.yml es el archivo de configuración predeterminado de Spring Boot y se cargará automáticamente. Supongamos que ahora tenemos un src / main / resources / person.properties:
person.lastName=Jhon
person.age=18
person.boss=false
person.birth=2020/03/21
person.maps.k1=v1
person.maps.k2=v2
person.lists=Tom,Sam
person.dog.name=small dog
person.dog.age=2
En primer lugar, SpringBoot no cargará este archivo de configuración personalizado, por lo que no podemos asignarlo con nuestra clase de configuración Person.java, por lo que podemos agregar la anotación @PropertySource a la clase de configuración para lograr la carga:
package com.wong.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 将配置文件中配置的每一个属性值,映射到这个组件中
* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定
* prefix = "person":配置文件中哪个下面的所有属性值进行一一映射
* 注意:只有这个组件是容器的组件,才能使用容器提供的ConfigurationProperties功能
* @PropertySource加载指定的配置文件
*/
@Configuration
@PropertySource("classpath:person.properties")
@ConfigurationProperties(prefix = "person")
public class Person{
private String lastName;
private int age;
private boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
// omit setter getter
}
@ImportResource se usa específicamente para cargar archivos de configuración de Spring
1. Defina el componente HelloService
package com.wong.service;
public class HelloService {
}
2. Cree un archivo de configuración Spring src / main / resources / beans.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloService" class="com.wong.service.HelloService"/>
</beans>
El valor de id es el identificador único del componente después de que se agrega al contenedor Spring.
3. Agregue esta anotación a la clase de configuración (la clase con la anotación @Configuration) para que se pueda cargar al inicio. Por conveniencia, ahora se coloca en la clase de inicio
package com.wong;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class MainApplication{
public static void main(String[] args){
SpringApplication.run(MainApplication.class,args);
}
}
4. Ejecute la clase de prueba src / test / java / com / wong / SpringBootConfigTests.java
package com.wong;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootConfigTests {
@Autowired
private ApplicationContext ioc;
@Test
public void testBeans(){
boolean b = ioc.containsBean("helloService");
System.out.println(b);// true
}
}
@Bean agrega componentes al contenedor
SpringBoot recomienda agregar componentes al contenedor de forma totalmente anotada:
- La clase de configuración es el archivo de configuración de Spring
- Use @Bean para agregar componentes al contenedor,
para que pueda reemplazar el método anterior de cargar el archivo de configuración de Spring usando @ImportResource con el siguiente método:
1. Cree una clase de configuración src / main / java / com / wong / config / AppConfig.java
package com.wong.config;
import com.wong.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public HelloService myHelloService(){
return new HelloService();
}
}
La anotación @Configuration hará que la clase de configuración se escanee al inicio.
@Bean colocará una instancia de HelloService en el contenedor Spring, y el único identificador es su nombre de método, como myHelloService en este ejemplo.
2. Ejecute la clase de prueba src / test / java / com / wong / SpringBootConfigTests.java
package com.wong;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootConfigTests {
@Autowired
private ApplicationContext ioc;
@Test
public void testMyHelloService(){
boolean b = ioc.containsBean("myHelloService");
System.out.println(b); // true
}
}