spring 运行时属性值注入

  继续spring学习,今天介绍两种外部属性值注入的方式。当你需要读取配置信息时,可以快速读取。

  开始之前先创建属性文件site.properties,放在classpath下面

#数据库配置 ###
database.oracle.platform=org.hibernate.dialect.Oracle9iDialect
database.mysql.platform=org.hibernate.dialect.MySQL5InnoDBDialect
database.sqlserver.platform=org.hibernate.dialect.SQLServerDialect

 1、使用@PropertySource注解和org.springframework.core.env.Environment。@PropertySource声明属性源,Environment用于检索属性值。

@Controller
@RequestMapping("/free")
@PropertySource("classpath:site.properties")
public class FreeMarkerController {
    @Autowired
    Environment env;
    
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String sayHelloAgain(ModelMap model) {
        model.addAttribute("greeting", "Freemarker Again, from Spring 4 MVC");
        model.addAttribute("mysql",env.getProperty("database.mysql.platform"));
        return "welcome2";
    }
}

 2、使用@Component注解和@Value注解。使用组件自动扫描方式,首先需要在beans配置文件中加载属性文件到spring上下文中,之后用@Value注解标注属性,用于自动组装。

  • 加载属性文件到spring上下文中(property-placeholder简捷易用,个人比较喜欢)
<!-- 引入配置文件的方法一 --> 
    <context:property-placeholder location="classpath:site.properties"/>   
    <!-- 引入配置文件的方法二 --> 
    <!--<bean id="freemarkerConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
        <property name="location" value="classpath:site.properties" />  
    </bean>-->
  • 创建属性组件,将POJO与属性文件关联起来
@Component
public class SiteProperties {
    @Value("${database.mysql.platform}")
    private String mysql;
    @Value("${database.oracle.platform}")
    private String oracle;
    @Value("${database.sqlserver.platform}")
    private String sqlserver;

    public String getMysql() {
        return mysql;
    }

    public String getOracle() {
        return oracle;
    }

    public String getSqlserver() {
        return sqlserver;
    }
}
  • 调用试试
    @Autowired
    SiteProperties site;
    
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String sayHelloAgain(ModelMap model) {
        List<ProcessBlock> list = processBlock.findByName("主干流程");
        System.out.println("主干流程描述:"+list.size());
        //long div =0L;
        //long per =  10/div;
        model.addAttribute("greeting", "Freemarker Again, from Spring 4 MVC");
        model.addAttribute("mysql",env.getProperty("database.mysql.platform"));
        model.addAttribute("oracle",site.getOracle());
        return "welcome2";
    }

     本次测试,到此结束。需要说明的是spring的注入还有其他的方式。个人比较喜欢这两种。当然,在这两者之间,我更喜欢第二种方法一些,用POJO方式进行属性管理,代码会更干净些。

每天都是崭新的开始 ——Mr.司满(214382122)[]~( ̄▽ ̄)~*
原文地址:https://www.cnblogs.com/MrSi/p/7985769.html