在一个SSH的项目中遇到一个问题,我有一个dao的接口BaseJdbcDao,和一个dao的实现类BaseJdbcDaoImpl,实现类已经通过注解提交给容器进行管理,然后有一个工具类MailHelper想通过自动装配载入dao的实现类,可是每次都没有装配成功,代码如下,请教各位:
[code="java"]
package base;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.support.rowset.SqlRowSet;
public interface BaseJdbcDao {
public abstract List queryForList(String sql);
public abstract int queryForInt(String sql);
public abstract SqlRowSet queryForRowSet(String sql);
public abstract int update(String sql);
public abstract Map queryForMap(String sql);
public abstract void delete(String sql);
public abstract void insert(String sql);
}
[/code]
[code="java"]
package base.impl;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import base.BaseJdbcDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository("basejdbcdao")
public class BaseJdbcDaoImpl implements BaseJdbcDao {
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
@Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List queryForList(String sql){
System.out.println(sql);
return this.getJdbcTemplate().queryForList(sql);
}
public int queryForInt(String sql){
System.out.println(sql);
return this.getJdbcTemplate().queryForInt(sql);
}
public SqlRowSet queryForRowSet(String sql){
System.out.println(sql);
return this.getJdbcTemplate().queryForRowSet(sql);
}
public int update(String sql){
System.out.println(sql);
return this.getJdbcTemplate().update(sql);
}
public Map queryForMap(String sql){
System.out.println(sql);
return this.getJdbcTemplate().queryForMap(sql);
}
public void delete(String sql){
System.out.println(sql);
this.getJdbcTemplate().update(sql);
}
public void insert(String sql){
System.out.println(sql);
this.getJdbcTemplate().execute(sql);
}
}
[/code]
[code="java"]package util;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import java.util.Date;
import javax.activation.DataHandler;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import util.ByteArrayDataSource;
import javax.mail.PasswordAuthentication;
import base.BaseJdbcDao;
import base.impl.BaseJdbcDaoImpl;
public class MailHelper {
@Autowired
@Qualifier("basejdbcdao")
private BaseJdbcDao dao;
private String email;
private String mobile;
private String school;
private String name;
private String remark;
private String appstr;
public MailHelper(String school,String name,String mobile,String email,String remark,String appstr){
this.email = email;
this.mobile = mobile;
this.school = school;
this.name = name;
this.remark = remark;
this.appstr = appstr;
}
public MailHelper(){};
public void sendMail(){
this.insertData(school,name,mobile,email,remark,appstr);
}
/**
* 帐号申请的功能
* @param template
* @param pschool
* @param pname
* @param pmobile
* @param pemail
* @param premark
*/
public void insertData(String pschool,String pname,String pmobile,String pemail,String premark,String appstr){
String email = changeContent( pemail);
String mobile = changeContent( pmobile);
String school =changeContent (pschool);
String name =changeContent (pname);
String remark = changeContent (premark);
String to = "test@163.com";
String subject = "申请";
StringBuilder sb = new StringBuilder("insert into maillist(linkman,school,mobile,mail,remark)values('"+name+"','"+school+"','"+mobile+"','"+email+"','"+remark+"')");
dao.update(sb.toString());
remark = "内容略。。";
this.send( to, subject, remark);
}
/**
* Sending a mail with given values.<br>
* content parameter means the main email text,it refers to a html file.
*
* @param smtpServer
* @param to
* @param from
* @param subject
* @param content
* @param emailUsername
* @param emailUserpass
* @author WYQ
*/
private String send(String to,String subject,String content) {
try {
HashMap<String,String> map = readParamters();
String smtpserver = map.get("smtpserver");
String publicaccount = map.get("publicaccount");
String publicpwd = map.get("publicpwd");
String from = map.get("publicmail");
Properties props = System.getProperties();
props.put("mail.smtp.port", "25");
props.put("mail.smtp.starttls.enable","false");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", smtpserver);
Session session = null;
session = Session.getDefaultInstance(props,new PasswordAuthenticator(publicaccount,publicpwd));
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse( to, false));
msg.setSubject(subject);
msg.setDataHandler(new DataHandler(new ByteArrayDataSource(content,"text/html; charset=\"utf-8\"")));
msg.setHeader("X-Mailer", "XML-Mail");
msg.setSentDate(new Date());
// -- Send the message --
Transport.send(msg);
return "success";
} catch (Exception ex) {
return "Error" + ex;
}
}
private HashMap<String,String> readParamters(){
HashMap<String,String> map = new HashMap<String,String>();
Properties properties =new Properties();
try {
properties.load(MailHelper.class.getClassLoader().getResourceAsStream("mail.properties"));
map.put("smtpserver", properties.getProperty("smtpserver"));
map.put("publicmail", properties.getProperty("publicmail"));
map.put("publicaccount", properties.getProperty("publicaccount"));
map.put("publicpwd", properties.getProperty("publicpwd"));
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
}
class PasswordAuthenticator extends Authenticator {
private String username;
private String password;
public PasswordAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (username, password);
}
}
[/code]
然后我在struts的action类中调用MailHelper的send方法进行邮件发送时,打印的dao总是为空,action的代码是:
[code="java"]
/**
* 帐号申请-邮件发送
* @return
*/
public String sendMail(){
MailHelper mh = new MailHelper();
mh.sendMail();
success = true;
return SUCCESS;
}
[/code]
spring的自动扫描和注解配置已经开启,也已经把dao的package路径和MailHelper的package路径加入到基类中了,
[code="java"]
[/code]
现在就是弄不明白,为什么通过new出来的MailHelper对象中注入的dao总是为空呢。
给你点代码片段,参考下:
[code="java"]
// dao
public class BaseDaoHibernate extends
HibernateDaoSupport implements BaseDao {
protected Class persistentClass;
@Autowired
public void setSessionFactory0(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
}
@Repository("authorizeDao")
public class AuthorizeDaoHibernate extends BaseDaoHibernate
implements AuthorizeDao {
private Criteria getAuthorizeCriteria(Authorize auth) {
Criteria crit = getCriteria();
Example example = Example.create(auth);
example.enableLike(MatchMode.ANYWHERE);
crit.add(example);
if (auth.getDate_s() != null) {
crit.add(Restrictions.ge("createDate", auth.getDate_s()));
}
if (auth.getDate_e() != null) {
crit.add(Restrictions.le("createDate", auth.getDate_e()));
}
return crit;
}
// service
@Service("authorizeService")
public class AuthorizeServiceImpl implements AuthorizeService {
@Autowired
private AuthorizeDao authorizeDao;
public Authorize getAuthorizeByAuthId(Long authId) {
return authorizeDao.getById(authId);
}
public List<Authorize> findAll() {
return authorizeDao.findAll();
}
//action
@SuppressWarnings("serial")
public class AdminAction extends AuthAction {
private SiteBackGroudUser user;
private Long keyId;
private List<Authorize> auths;
private Page page;
@Autowired
private SiteBackGroudUserService siteBackGroudUserService;
@Autowired
private AuthorizeService authorizeService;
[/code]
applicationContext.xml
[code="xml"]
<?xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
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-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- ========================= RESOURCE DEFINITIONS ========================= -->
<!-- Configurer that replaces ${...} placeholders with values from a properties
file -->
<!-- (in this case, JDBC-related settings for the dataSource definition
below) -->
<context:property-placeholder
location="classpath:jdbc.properties,classpath:chinapay_conf.properties,classpath:unionpay_conf.properties" />
<!-- Uses Apache Commons DBCP for connection pooling. See Commons DBCP documentation
for the required JAR files. Alternatively you can use another connection
pool such as C3P0, similarly configured using Spring. -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource">
<property name="packagesToScan" value="com.yintong.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
<prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
<prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
<!-- 缓存配置 -->
<prop key="hibernate.cache.provider_class">org.hibernate.cache.OSCacheProvider</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.search.default.directory_provider">org.hibernate.search.store.FSDirectoryProvider
</prop>
<prop key="hibernate.search.default.indexBase">E:/indexes
</prop>
</props>
</property>
<property name="eventListeners">
<map>
<entry key="merge">
<bean
class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener" />
</entry>
</map>
</property>
</bean>
<!-- Transaction manager for a single Hibernate SessionFactory (alternative
to JTA) -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= -->
<!-- Activates various annotations to be detected in bean classes: Spring's
@Required and @Autowired, as well as JSR 250's @Resource. -->
<context:annotation-config />
<context:component-scan
base-package="com.dao.hibernate,
com.service.impl," />
<!-- Instruct Spring to perform declarative transaction management automatically
on annotated classes. -->
<tx:annotation-driven />
<!-- Exporter that exposes the Hibernate statistics service via JMX. Autodetects
the service MBean, using its bean name as JMX object name. -->
<context:mbean-export />
[/code]
spring和struts2的结合不需要配置,因为struts默认 spring 自动注入,只要保持你声明的@Service("authorizeService")中的名称与action中该对象的变量名一样就行。
你这样当然不可以了。你应该将MailHelper对象注入到你的action类中,而不是new一个出来。
spring自动装载也是将其类的实例装载到自己的容器中,也就是所谓的上下文中(context).对象的创建都是托管给spring容器的。使用new时当然得不到其对象及其对象以来的dao了。
你可以在你的action中声明一个MailHelper,然后提供其自动注入,并将你的MailHelper标注为一个容器@Resource,让spring管理struts,这样你就可以直接MailHelper而不需要new了。否则你只能读取spring的applicationContext.xml拿到AnnotationConfigApplicationContext对象使用getBean获取MailHelper实例了。
new当然不行了,单纯new的话不用spring管理的话,是不会理会注入啊 注解之类的
总之不是这样玩的 你用new就是你玩你自己的根本没告诉spring这个大管家