Spring annotation-driven development-attribute assignment

Foreword

  In actual development, it is not too much to directly assign the attribute of the bean in Spring. Organize the information in this area and make a summary for the further study in the future.

Through the configuration file

When the spring container is started in the configuration file, you can use the value of the property tag to assign values ​​to the properties of the bean. The forms of assignment are as follows:

<-Environment variables loaded in the properties file through context: property-placeholder ( the property values in properties are ultimately stored in the form of environment variables )> 
<context: property-placeholder location = "classpath: person. properties "/>
<bean id =" person " class =" com.atneusoft.bean.Person ">
< -① Direct assignment through basic values- > <property name =" name "value =" zhangsan "> </ property>
< -②Retrieve the value in the configuration file through $ {} ->
        <property name="age" value="${person.age}"></property>
   <--③通过Spring的El表达式-->
     <--<property name="age" value="10*2"></property>-->
</bean>

Contents of properties file under classpath

person.age=\u5C0F\u674E\u56DB

By annotation

Use the annotation corresponding to the value of properties to assign a value to the property

// Use @PropertySource to read the k / v in the external configuration file and save it to the running environment variable; after loading the external configuration file, use $ {} to extract the value of the configuration file 
@PropertySource (value = {"classpath: / person .properties " }) 
@Configuration 
public  class MainConfigOfPropertyValues ​​{ 
    
    @Bean 
    public Person person () {
         return  new Person (); 
    } 

}

 

public  class Person { 
    
    // Use @Value assignment;
     // 1, basic value
     // 2, can write SpEL; # {}
     // 3, can write $ {}; take out the value in the configuration file [properties] (in operation Values ​​in environment variables) 
    
    @Value ( " 张三 " )
     private String name; 
    @Value ( "# {20-2}" )
     private Integer age; 
    
  / * @Value ("$ {person.age}") 
    private Integer age; * / }

Note:

The k / v in the external configuration file is saved to the running environment variable, and the corresponding value can be taken directly from the environment variable
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        String property = environment.getProperty("person.age");

 

Guess you like

Origin www.cnblogs.com/tombky/p/12683767.html