如何将属性文件中的值保存到类中

一、将属性文件中的值保存到类中

  1、编写属性文件,以键值对形式存储,并放置在类路径(src)下

  jdbc.jdbcUrl=jdbc:mysql://localhost:3306/BOOKSTORE?rewriteBatchedStatements=true
  jdbc.user=bookmanager
  jdbc.password=manager
  jdbc.driverClass=com.mysql.jdbc.Driver

  2、在ApplicationContext.xml配置文件中配置属性文件

  <context:property-placeholder location="classpath:jdbc.properties"/>

  3、类需要加上@Controller注解,在目标属性上加@Value注解,即可将属性文件中的值赋值给类的属性

 1   package com.neuedu.spring.controller;
 2 
 3   import org.springframework.beans.factory.annotation.Value;
 4   import org.springframework.stereotype.Controller;
 5 
 6   @Controller
 7   public class MyController {
 8       @Value(value="${jdbc.user}")   //将属性文件中jdbc.user的值赋值给username
 9       private String username;
10   }

  4、在ApplicationContext.xml文件中配置扫描包,扫描MyController类所在的包

  <context:component-scan base-package="com.neuedu.spring.controller"></context:component-scan>

  5、在ApplicationContext.xml文件中创建Controller类的bean对象

  <bean id="myController" class="com.neuedu.spring.controller.MyController"></bean>

  测试代码:

1   @Test
2     public void test() throws Exception {
3         MyController myController = ioc.getBean(MyController.class);
4         System.out.println(myController);
5     }

 

posted @ 2017-12-08 09:06  咕噜噜zmj  阅读(391)  评论(0编辑  收藏  举报