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

2021-02-19 21:31

阅读:928

标签:integer   开发   el表达式   前言   getenv   ati   环境变量   内容   value   

前言

  在实际开发当中,Spring中bean的属性直接赋值用的不是太多,整理这方面的资料,做一个小结,以备后续更深入的学习。

通过配置文件的方式

以配置文件的方式启动spring容器时,可以使用property标签的value给bean的属性赋值,赋值的形式有以下几种:

properties中的属性值最终是以环境变量的形式存储的)>

class="com.atneusoft.bean.Person" >
①通过基本数值直接赋值-->
②通过${}取出配置文件中的值-->
        
   ③通过Spring的El表达式-->
     -->


classpath下的properties文件内容

person.age=\u5C0F\u674E\u56DB

通过注解的方式

使用properties的value对应的注解给属性赋值

//使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用${}取出配置文件的值
@PropertySource(value={"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {
    
    @Bean
    public Person person(){
        return new Person();
    }

}

 

public class Person {
    
    //使用@Value赋值;
    //1、基本数值
    //2、可以写SpEL; #{}
    //3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值)
    
    @Value("张三")
    private String name;
    @Value("#{20-2}")
    private Integer age;
    
  /*  @Value("${person.age}")
    private Integer age;*/ }

注:

外部配置文件中的k/v保存到运行的环境变量中,可以直接在环境变量中取出对应的值
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        String property = environment.getProperty("person.age");

 

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

标签:integer   开发   el表达式   前言   getenv   ati   环境变量   内容   value   

原文地址:https://www.cnblogs.com/tombky/p/12683767.html


评论


亲,登录后才可以留言!