spring 用法 源码解析 注意

spring 注解开发

属性赋值

@Value

@Value

  • 基本值
  • SpEL, #{}
  • ${}, 取出配置文件[properties]中的值(在运行环境变量里面的值)

用法

@Value

@Value("张三")
private String name;

@Value("#{20-2}")
private String age;


@Value("${jdbc_url}")
private String jdbcUrl;

/**
 *  使用 @PropertySource 读取外部配置文件中k/v保存在运行的环境变量中
 * @author TrueBt
 */
@PropertySource({"classpath:/person1.properties"}) 
@PropertySource({"classpath:/person2.properties"})   
@PropertySources({@PropertySource("/person1.properties"), @PropertySource("/person2.priperties")})
@Configuration
public class MainConfigPropertyValue {
    @Bean
    public Person person(){
        return new Person();
    }
}
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigPropertyValue.class);
Person bean = context.getBean(Person.class);

//通过环境获取
System.out.println(context.getEnvironment().getProperty("person.nickname"));
System.out.println(bean);

源码解析

注意