SpringMVC key-value读取properties配置文件

环境:IDEA 2018.1

1、项目结构如图

其中,配置的文件包括User、MainController、info.properties、springmvc.xml,都是手动建立,最后一个在xml configuration file中选为了spring config。

第一步  建立info.properties属性文件。

name=123
password=123

因为是测试,所以比较简单

第二步  建立User ,就是普通的数据类,没有加入注解。

public class User {
    private String username;

    private String password;

    public void setUsername(String username){
        this.username = username;
    }

    public String getUsername(){
        return username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

尝试过@value方法,且题主希望在main方法中输出结果,但static方法不适用,又需要new一个对象再获取属性值,几次获取到属性值为null,放弃。

第三步  配置springmvc.xml,为了避免路径问题,放在了根目录下。这一步最重要。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">

    <context:property-placeholder location="classpath:info.properties"/>
    <bean id="user" class="Beans.User">
        <property name="username" value="${name}" />
        <property name="password" value="${password}" />
    </bean>

</beans>

解释:

  • <context:property-placeholder>加载配置文件

  • 下面的bean标签与User对应,id自己定,class定位到类的位置,property对应着属性,value对应的是在属性文件中的key值

容易出现的问题:

  • <context:property-placeholder>无法识别,显示cannot resolve symbol之类的,我通过加入这三项加以解决的,注意版本号

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd

  • property中name显示cannot resolve property之类的,用和User中相同的属性名就能解决,正确情况会有提示

第四步  真正读取属性文件中的值进行显示,配置MainController,此处就相当于一个测试类。

public class MainController {

    public static void main(String[] args) {
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("springmvc.xml");
        User user=(User) applicationContext.getBean("user");
        System.out.println("name="+user.getUsername());
        System.out.println("age="+user.getPassword());
    }

}

getbean对应的是第四步中的id。尝试过@Component("user")的方式进行,失败,显示不能获得对应的bean。这个方法结合官方文档和其他博客,像我一样的新手建议多参考文档,避免配置不全,理解错乱。

输出结果

忽略水印,以上仅供参考。

猜你喜欢

转载自blog.csdn.net/ChristineAS/article/details/81217597