日期:2014-05-19  浏览次数:20721 次

Spring注解问题
Java code

@Service
public class MessageUtil {
   ...
}

@Controller
public class UserAction extends ActionSupport{

    private static final long serialVersionUID = 1L;
    
    @Resource(type=MessageUtil.class)
    private MessageUtil messageUtil;
    
    public String addUser() throws Exception{
        System.out.println("进入---------");
        return messageUtil.sendMsg("ddif");
    }

    public MessageUtil getMessageUtil() {
        return messageUtil;
    }

    public void setMessageUtil(MessageUtil messageUtil) {
        this.messageUtil = messageUtil;
    }

}


上面的这段代码从action中取不到messageUtil,
java.lang.NullPointerException
com.xosou.web.action.system.UserAction.addUser(UserAction.java:27)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:453)
com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:292)

但是用Junit就可以取到
Java code

    @Test
    public void testb() throws Exception{
        String[] path = new String[] { "config/applicationContext.xml" };
        ApplicationContext ac = new ClassPathXmlApplicationContext(path);
        MessageUtil p = (MessageUtil) ac.getBean("messageUtil");
        p.sendMsg("ab", null);
    }



------解决方案--------------------
接口注入,MessageUtil是一个类
------解决方案--------------------
@Resource(type=MessageUtil.class) 换成@Autowire 看看 然后spring配置文件要加入自动去扫描你的MessageUtil上面的包
------解决方案--------------------
换成@Autowire 是个正确的选择,而且你在xml文件中要加入

<context:component-scan base-package="*.*.*">
<context:include-filter expression="org.aspectj.lang.annotation.Aspect"
type="annotation" />
<context:exclude-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan>
其中*.*.*表示你的外层的package的结构,系统启动时,会对这个package下的注解进行自动注入
------解决方案--------------------
给它一个空的构造方法 试试