SpringMVC通过注解@Value获取properties配置

SpringMVC中有两个xml配置文件:

1、applicationContext.xml,这个是Spring的主配置文件,包括dao层service层的bean定义或扫描、数据源、事务等的配置信息。

2、xxx-servlet.xml,这个是mvc的配置文件,包括controller层的bean定义或扫描、静态资源访问以及view配置

properties配置文件中的信息定义在applicationContext.xml中,那么在service层使用@Value注解即可访问到,但在Controller层使用@Value注解却不能访问到。

若要在Controller层也使用@Value访问properties配置的话,需要在xxx-servlet.xml中也定义properties配置文件。

properties文件在spring配置文件xml中定义如下:


[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <context:property-placeholder  
  2.         location="file:${user.dir}/persona/conf/datasource.properties,file:${user.dir}/persona/conf/system.properties"  
  3.         ignore-unresolvable="true" />  

注:${user.dir}为tomcat下的bin目录,不用定义可以直接使用


db.properties文件:

[plain]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. dburl=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8  
  2. dbusername=root  
  3. dbpassword=123456  

使用@Value访问:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Value("${dburl}")  
  2. private String dburl;  

猜你喜欢

转载自blog.csdn.net/wylfll/article/details/72177317