美文网首页spring碎片知识辑
SpringMVC通过注解@Value获取properties配

SpringMVC通过注解@Value获取properties配

作者: 熊熊要更努力 | 来源:发表于2018-02-11 19:41 被阅读263次

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中定义如下:

    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文件:

  1.  dburl=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8  
  2.  dbusername=root  
  3.  dbpassword=123456  

使用@Value访问:

1.  @Value("${dburl}")  
2.  private String dburl;

相关文章

网友评论

    本文标题:SpringMVC通过注解@Value获取properties配

    本文链接:https://www.haomeiwen.com/subject/zddltftx.html