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属性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pascalzhli

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值