L'utilisation de @PropertySource, @ImportResource, @Bean dans le projet SpringBoot

@PropertySource charge le fichier de configuration spécifié

application.properties ou application.yml est le fichier de configuration par défaut de Spring Boot et sera chargé automatiquement. Supposons que nous ayons maintenant 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

Tout d'abord, ce fichier de configuration personnalisé ne sera pas chargé par SpringBoot, nous ne pouvons donc pas mapper avec notre classe de configuration Person.java, nous pouvons donc ajouter l'annotation @PropertySource à la classe de configuration pour effectuer le chargement:

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 est spécifiquement utilisé pour charger les fichiers de configuration Spring

1. Définissez le composant HelloService

package com.wong.service;

public class HelloService {
}

2. Créez un fichier de configuration 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>

La valeur de id est l'identifiant unique du composant après son ajout au conteneur Spring.
3. Ajoutez cette annotation à la classe de configuration (la classe avec l'annotation @Configuration) afin qu'elle puisse être chargée au démarrage. Pour plus de commodité, elle est désormais placée dans la classe de démarrage

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. Exécutez la classe de test 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 ajoute des composants au conteneur

SpringBoot recommande d'ajouter des composants au conteneur de manière entièrement annotée:

  • La classe de configuration est le fichier de configuration Spring
  • Utilisez @Bean pour ajouter des composants au conteneur,
    afin de pouvoir remplacer la méthode ci-dessus de chargement du fichier de configuration Spring à l'aide de @ImportResource par la méthode suivante:

1. Créez une classe de configuration 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();
    }
}

L'annotation @Configuration entraînera l'analyse de la classe de configuration au démarrage.
@Bean placera une instance de HelloService dans le conteneur Spring, et le seul identificateur est son nom de méthode, tel que myHelloService dans cet exemple.
2. Exécutez la classe de test 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
    }

}

Publié 381 articles originaux · loué 85 · 80 000 vues +

Je suppose que tu aimes

Origine blog.csdn.net/weixin_40763897/article/details/105107499
conseillé
Classement