Spring运行时候值注入

先来说一下问题

像这种直接输入值得方式叫做硬编码,我们要避免硬编码值,这时候如果我们想这些书名和作者名在运行时候再确认。

//novel类的构造方法里面的两个形参分为书名和作者名
@Bean
public Book firstbook(){
    return  new novel("斗破苍穹","天蚕土豆");
}

有两种方式可以实现运行时注入值

  • 属性占位符(Prototype placeholder)。
  • Spring表达式语言(SpEL)。

使用@PropertySource注解和Environment

@Configuration
@PropertySource("classpath:/com/spring/hjsjy/hj.properties")//引用了类路径hj.properties的文件。  
public class ExpressiveConfig{
    @Autowired
    Environment env;
   @Bean
public Book firstbook(){
    return  new novel(env.getProperty("hjsjy.title"),env.getProperty("hjsjy.author"));
}
}

这个属性文件会加载到Environment里面。
hjsjy.properties

hjsjy.title="斗破苍穹"
hjsjy.author="天蚕土豆"

我们修改值的时候就在hjsjy.properties文件修改title和author来实现,这样就实现了运行时候值注入
使用占位符(${…})

<bean id="firstbook" 
      class="com.spring.hjsjy.Book"
      c:_titile=${hjsjy.titile}
      c:_author=${hjsjy.suthor}/>
public novel(
@value("${hjsjy.title}") String title,
@value("${hjsjy.author}") String author){
this.title=title;
this.author=author;}

使用占位符要配置一个PropertyPlaceholderConfigurer bean,他可以基于Spring Environment及其属性源来解析占位符。

  • 在java中配置
   @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){
        return new PropertySourcesPlaceholderConfigurer();
    }
  • 在xml中配置
<context:property-placeholder/>

本文参考资料:《spring实战(第四版)》

原文地址:https://www.cnblogs.com/narojay/p/10812608.html