Desarrollo impulsado por anotaciones de primavera [asignación de 03 atributos]

Desarrollo impulsado por anotaciones de primavera [asignación de atributos]

@Valor

  • Generar clases de entidad
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    
    
    /*
        使用@Value赋值:
    *       1.基本赋值 直接用 "(value)"
            2.SpringEL #{}	spring表达式内部可做运算等
    *       3.${} 取出配置文件[properties]中的值(运行环境变量中的值)
    *
    * */
    @Value("zs")
    private String name;
    @Value("#{20-2}")
    private Integer age;

    @Value("${person.sex}")
    private String sex;
}

  • person.properties
person.sex=male
  • Clase de configuración
@Configuration
//使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中
//加载完外部配置文件后使用${key}取出配置文件中的value
@PropertySource(value = {
    
    "classpath:/person.properties"})
//同样也可以通过@PropertySources{@PropertySource...}进行嵌套使用
public class ConfigOfPropertyValues {
    
    
    @Bean
    public Person person(){
    
    
        return new Person();
    }
}

  • Clase de prueba
public class TestPropertyValue {
    
    
	// 获取ioc容器
    ApplicationContext context = new AnnotationConfigApplicationContext(ConfigOfPropertyValues.class);

    @Test
    public void test() {
    
    
        getAllBeans(context);
        Person person = context.getBean("person", Person.class);
        System.out.println(person);

    }

    //	封装了获取ioc容器内部bean名字的方法
    public void getAllBeans(ApplicationContext context) {
    
    
        String[] beanDefinitionNames = context.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
    
    
            System.out.println(beanDefinitionName);
        }
    }
}

El resultado de la operación es

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
configOfPropertyValues
person
Person(name=zs, age=18, sex=male)

Se puede ver que se obtiene el atributo sex en el archivo de propiedades.

  • Agregado @PropertySource, también puede obtener propiedades obteniendo y ejecutando el entorno

     		Environment environment = context.getEnvironment();
            String property = environment.getProperty("person.sex");
            System.out.println(property);
    

Obtener la propiedad person.sex

Supongo que te gusta

Origin blog.csdn.net/weixin_45729934/article/details/108692280
Recomendado
Clasificación