5

spring框架用注解的方式装配属性为什么老是空指针异常

UserDao的实现类UserDaoImp
package com.two;

import org.springframework.stereotype.Repository;

@Repository("userDao")
public class UserDaoImp implements UserDao {

@Override
public void say() {
    // TODO Auto-generated method stub
    System.out.println("dao say hello spring");
}

}
UserService 的实现类UserServiceImp
package com.two;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

@Service ("userService")
public class UserServiceImp implements UserService {
@Resource(name="userDao")
public UserDao userDao;

public void say() {
    this.userDao.say();
    // TODO Auto-generated method stub
    System.out.println("service say hello spring");
}

}
bean.xml
<?xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">

<bean id="userDao" class="com.two.UserDaoImp"/>
<bean id="userService" class="com.two.UserServiceImp"/>


测试类Test
package com.two;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

public static void main(String[] args) {
    String xmlPath="com/two/bean.xml";
    // TODO Auto-generated method stub
    ApplicationContext applicationcontext=
            new ClassPathXmlApplicationContext(xmlPath);
    UserServiceImp userdao=(UserServiceImp) applicationcontext.getBean("userService");
    userdao.say();
}

}
错误提示
Exception in thread "main" java.lang.NullPointerException
at com.two.UserServiceImp.say(UserServiceImp.java:13)
at com.two.Test.main(Test.java:14)

查看全部
wushengchenyu
行业混子
2019/01/18 23:39
  • spring
  • 点赞
  • 收藏
  • 回答
    私信

3个回复