①常量注入
@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'}
容器创建完成
本文通过实例展示了Spring Boot中使用@Value注解进行常量注入、SpEL表达式计算以及从properties文件中读取属性值的方法。在Bird实体类中,分别注入了名称、年龄和颜色属性,并在测试类中展示了如何通过配置类和属性文件创建并打印Bird对象。测试结果显示,Bird对象的属性被正确地注入和计算。
1260

被折叠的 条评论
为什么被折叠?



