最近试着做了个springmvc 项目,在加入 发邮件 功能时遇到的问题。
Spring 通过注解获取*.porperties文件的内容,除了xml配置外,还可以通过@value方式来获取。
@value是需要spring注解扫描的,所以要将spring注解扫描配置中加上实体类的包名路径,实体类中也应添加@Component
@Component
public class MailBean {
//实体类前加@Component ,让spring扫描到该实体类,默认是单例模式,该实体类的功能是从 资源文件中读取对应的内容
@Value("#{configProperties['emailhost']}")
private String emailHost;
@Value("#{configProperties['emailform']}")
private String emailFrom;
@Value("#{configProperties['emailname']}")
private String emailUsername;
@Value("#{configProperties['emailpassword']}")
private String emailPassword;
public String getEmailHost() {
return emailHost;
}
public String getEmailFrom() {
return emailFrom;
}
public String getEmailUsername() {
return emailUsername;
}
public String getEmailPassword() {
return emailPassword;
}
spring配置文件部分代码如下
<!-- 自动扫描bugkiller包 ,将带有注解的类 纳入spring容器管理 -->
<context:component-scan base-package=""></context:component-scan>
<!-- 引入配置文件 -->
<bean class="">
<property name="locations">
<list>
<value>classpath:</value>
<value>classpath:</value>
</list>
</property>
</bean>
<bean class="">
<property name="properties" ref="configProperties" />
</bean>
资源文件内容为
emailhost=邮箱的网关
emailname=你的用户名
emailpassword=你的密码
emailform=发件邮箱 //具体值需根据自身情况配置
这样配置完了,从junit测试中可以正常取到 properties中配置的值
@Test
public void test(){
ApplicationContext appContext = new ClassPathXmlApplicationContext("");
MailBean connInfo = ();
(());
(());
<span style="white-space:pre"> </span>//可以正常获取<span style="white-space:pre"> </span>
(());
}
但一在具体业务中使用的时候get到的是null
后来发现原来我在业务中还是用的 new来创建的实体类 Mailbean ,但Mailbean 已经通过@Component 加入了Spring的管理中了,并且默认的单例,直接new肯定是不对的 ,所以在业务中通过 @Resource private MailBean mailBean; 注入进来,当然该业务类之前也要加注释交给spring管理, 这样就能成功的取到值了,在junit测试时是通过
MailBean connInfo = ();
获取的bean,所以能正常取值,在业务中的话记得要通过@resource 注入进来,不然是获取不到该bean的奥,
另外在修改spring 配置文件时,添加如下代码时会抛出一些警告,说是没有权限创建某些文件
<bean class="">
<property name="locations">
<list>
<value>classpath:</value>
<value>classpath:</value>
</list>
</property>
</bean>
警告 : Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002. Windows RegCreateKey 等等。。。
应该实在写入注册表是权限不够引起的 ,只需在命令窗口打开 regedit注册表管理,在 HKEY_LOCAL_MACHINE\Software\JavaSoft\ 下创建 Prefs项即可