Spring 注解驱动开发【03-属性赋值】

Spring 注解驱动开发【属性赋值】

@Value

  • 生成实体类
@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
  • 配置类
@Configuration
//使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中
//加载完外部配置文件后使用${key}取出配置文件中的value
@PropertySource(value = {
    
    "classpath:/person.properties"})
//同样也可以通过@PropertySources{@PropertySource...}进行嵌套使用
public class ConfigOfPropertyValues {
    
    
    @Bean
    public Person person(){
    
    
        return new Person();
    }
}

  • 测试类
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);
        }
    }
}

运行结果为

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)

可见获取到了property文件中的sex属性

  • 添加了@PropertySource同样可以通过获取运行environment的方法获取到属性

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

获取到person.sex属性

猜你喜欢

转载自blog.csdn.net/weixin_45729934/article/details/108692280