①常量注入
@Value("喜鹊")
private String name;
②SpEL表达式
@Value("#{20-8}")
private Integer age;
③从properties文件中读取属性值
@Value("${bird.colour}")
private String colour;
1、实体类
import org.springframework.beans.factory.annotation.Value;
public class Bird {
@Value("喜鹊")
private String name;
@Value("#{20-8}")
private Integer age;
@Value("${bird.colour}")
private String colour;
@Override
public String toString() {
return "Bird{" +
"name='" + name + '\'' +
", age=" + age +
", colour='" + colour + '\'' +
'}';
}
}
2、test.properties
bird.colour = red
3、配置类
import com.it.huaxin.vo.Bird; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @PropertySource(value = {"classpath:/test.properties"}) @Configuration public class BirdConfig { @Bean public Bird bird () { return new Bird(); } }
4、测试类
import com.it.huaxin.config.BirdConfig; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class BirdTest { public static void main(String [] args) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BirdConfig.class); Object bird = applicationContext.getBean("bird"); System.out.println(bird); System.out.println("容器创建完成"); applicationContext.close(); } }
5、测试结果
Bird{name='喜鹊', age=12, colour='red'}
容器创建完成