java中@value的环境配置

@value

在现阶段我想大家对注解都不陌生,@value的用法就是在后台获取配置文件的信息,从而方便修改一些固定的配置。不明白的可以百度@value的详解。

配置@value有以下几个步骤。

1、首先新建一个配置文件,system.properties

目录结构如下图

内容如下

jdbc.jdbcUrl=jdbc:mysql://localhost:3306/commentDemo?useUnicode=true&characterEncoding=UTF-8 

2、配置xml文件。就是spring的那个配置文件,添加如下内容

<!-- @value注解 -->
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
            <value>WEB-INF/config/system.properties</value>
        </list>
    </property>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
    <property name="properties" ref="configProperties" />
</bean>

3、在controller中使用

@Controller
@RequestMapping("userManager")
public class UserController extends BaseController{
    
    @Value("#{configProperties['jdbc.jdbcUrl']}")  
    private String jdbcUrl;
    
    @Resource
    private UserDao userDaoImpl;
    
    @RequestMapping(value="/showList")
    public String showList(Model model){
        
        System.out.println(jdbcUrl);
        return "index";
    }

4、查看结果如下

原文地址:https://www.cnblogs.com/wangxiangstudy/p/5178972.html