8
回答
struts2.3.4,spring3.2.0,hibernate3整合 action中的service获取null,spring注入不进来。
开发十年,就只剩下这套Java开发体系了   

struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
	<constant name="struts.devMode" value="true" />
    <package name="default" namespace="/" extends="struts-default">

        <action name="user" class="userAction">
            <result name="success">/Hello.jsp</result>
            <result name="fail">/Fail.jsp</result>
        </action>    

    </package>
</struts>

beans.xml:



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xmlns:aop="http://www.springframework.org/schema/aop"
     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/tx
         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

   <context:annotation-config />
   <context:component-scan base-package="com.ssh"/>
   
   <bean id="dataSource" 
        class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
	    <property name="driverClassName" value="${jdbc.driverClassName}"/>
	    <property name="url" value="${jdbc.url}"/>
	    <property name="username" value="${jdbc.username}"/>
	    <property name="password" value="${jdbc.password}"/>
	</bean>
	<context:property-placeholder location="classpath:jdbc.properties"/>
	
	<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
	    <property name="dataSource" ref="dataSource"/>
	    <property name="annotatedClasses">
	      <list>
	        <value>com.ssh.model.User</value>
	      </list>
	    </property>
    	<property name="hibernateProperties">
	      <props>
	          <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
	          <prop key="hibernate.show_sql">true</prop>
	      </props>
    	</property>
  </bean>
  
		
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		  <property name="sessionFactory" ref="mySessionFactory" />
	</bean>
	
	<aop:config>
	    <aop:pointcut expression="execution(public * com.ssh.service.*.*(..))" id="serviceOperation"/>
	    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation"/>
	</aop:config>
	
	<tx:advice id="txAdvice" transaction-manager="txManager">
	    <tx:attributes>
	        <tx:method name="checkUserName" read-only="true"/>
	        <tx:method name="add*" propagation="REQUIRED"/>
	    </tx:attributes>
	</tx:advice>
	
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="mySessionFactory"></property>    	    
	</bean>
</beans>


web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

    <!-- 指明spring配置文件在何处 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/classes/beans.xml</param-value>
    </context-param>

    <!-- 加载spring配置文件applicationContext.xml -->
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>   
  
    <!-- 加载struts2核心 -->
    <filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>		
  
</web-app>
UserAcion.java:

package com.ssh.action;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;
import com.ssh.model.User;
import com.ssh.service.UserService;

@Component
public class UserAction extends ActionSupport{

	private static final long serialVersionUID = 1L;
		
	private String username;
	private String password;
	private UserService userService;
	
	@Override
	public String execute() throws Exception {
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		
		if(userService.checkUserName(user)) {
			return "fail";
		}
		
		userService.add(user);		
		return "success";
	}
	
	public UserService getUserService() {
		return userService;
	}
	
	@Resource(name="userService")
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	
}
UserServiceImpl.java

package com.ssh.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.ssh.dao.UserDao;
import com.ssh.model.User;
import com.ssh.service.UserService;

@Component
public class UserServiceImpl implements UserService{
	
	private UserDao userdao;

	public UserDao getUserdao() {
		return userdao;
	}
	
	@Resource(name="userDaoimpl")
	public void setUserdao(UserDao userdao) {
		this.userdao = userdao;
	}
	
	@Override
	public void add(User user) {
		userdao.save(user);
	}
	
	@Override
	public boolean checkUserName(User user) {
		return userdao.checkUserExistByName(user.getUsername());
	}
	
}
已经加入了struts2-spring-plugin-2.3.4.jar和ssh中必要的jar.后台不报错,就是获取不到action中的service。想不明白。求大家帮助。

举报
何粤威
发帖于6年前 8回/4K+阅
共有8个答案 最后回答: 6年前
我已经把问题解决了,其实是我的包有点错乱了,我把所以的包都删了,再重新导进了Lib后就能运行了。

UserServiceImpl.java的@Component加参数@Component("userService")

Spring的自动加载默认是把类短名的首字母小写做bean的name。或者注入的地方@Resource的name指定成userServiceImpl

--- 共有 1 条评论 ---
何粤威对不起。题目有个地方打错了,我修改了下,还是获取null 6年前 回复

啊。对不起,

@Resource(name="userService")
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

这里写错了,应该是:

@Resource(name="userServiceImpl")
修改下问题。获得还是null。

那就不清楚了,写正确还是没取到,没遇到过呢。可以在setter方法上加个@Required看他要注入的究竟是什么。另外可以考虑改一下log4j的配置,让Spring的debug日志全部输出来,里面有每个bean初始化的相关信息:


#system log-------------------------------- 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %l %c%n%p: %m%n

log4j.rootLogger=info, stdout

# Spring
log4j.logger.org.springframework=debug, stdout

# Druid
log4j.logger.druid.sql=warn, stdout
log4j.logger.druid.sql.DataSource=warn, stdout
log4j.logger.druid.sql.Connection=warn, stdout
log4j.logger.druid.sql.Statement=warn, stdout
log4j.logger.druid.sql.ResultSet=warn, stdout

# Struts2
log4j.logger.org.apache.struts2=warn, stdout

# Project
log4j.logger.cn.org.sysu.cems=warn, stdout
log4j.logger.cn.org.sysu.cems.util.dbtemplate=debug, stdout
log4j.logger.cn.org.sysu.cems.util.debug=debug, stdout


@Resource(name="userService")不应该写到setUserDao上吧。。要写到private  UserDao userdao;这个上面吧
--- 共有 2 条评论 ---
54mark@何粤威 哦。不好意思...我一直用属性注入.没怎么玩过set注入 6年前 回复
何粤威.你那是属性注入。和set方法注入一样的。 6年前 回复

引用来自“何粤威”的答案

我已经把问题解决了,其实是我的包有点错乱了,我把所以的包都删了,再重新导进了Lib后就能运行了。
.
顶部