我在Service类中使用Autowired注释来注入Dao依赖项。我写的代码是:
public interface Service {
public List<String> getAllCountries() ;
}
public class ServiceImpl implements Service {
@Autowired
private TestDao testDao;
public TestDao getTestDao() {
return testDao;
}
public void setTestDao(TestDao testDao) {
this.testDao = testDao;
}
public List<String> getAllCountries() {
// TODO Auto-generated method stub
System.out.println("coming in here:" + testDao);
return testDao.getAllCountries();
}
}
public interface TestDao {
List<String> getAllCountries() ;
}
public class TestDaoImpl implements TestDao{
@Override
public List<String> getAllCountries() {
// TODO Auto-generated method stub
List<String> ls = new ArrayList<>();
ls.add("test1");
return ls;
}
}
And a controller
public class TestController {
public void doSth() {
Service service = new ServiceImpl();
try {
System.out.println("service obj:" + service);
List<String> list = service.getAllCountries();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
beans.xml中:
<context:annotation-config/>
<bean id="controller" class="org.test.TestController"/>
<bean id="testDao" class="org.test.TestDaoImpl"/>
And a main class:
ApplicationContext context = new
ClassPathXmlApplicationContext("beans4.xml");
TestController obj= (TestController) context.getBean("controller");
obj.doSth();
但它在ServiceImpl类中抛出NullPointerException
。这些所有类都在同一个包中。
有人可以帮我理解究竟是什么问题吗?
解决方案: 公共类TestController {
@Autowired
Service service;
//remaining code as it is
}
答案 0 :(得分:1)
您的Service类不受Spring管理。因此,依赖性正在被注入。
要管理您的服务类,
您可以使用@Service
立体声类型注释并进行分量扫描。
我的意思是,
package com;
@Service
public class ServiceImpl implement XXXX{
//Your changes
}
并在spring配置文件中:
<context:component-scan base-package="com"/>
答案 1 :(得分:0)
您的testDao
依赖bean尚未注入,您需要使用注释的Spring容器,并通过添加以下内容指定需要扫描的包以进行自动装配:< / p>
<context:annotation-config />
<context:component-scan base-package="org.test" />
您可以查看here如何自动连接弹簧豆。
答案 2 :(得分:0)
我没有看到ServiceImpl的任何bean声明或注释。
//You canot do it like the following
@controller
class A{
ServiceImpl simp=new ServiceImpl();
}
class ServiceImpl{
@Autowired
Adao adoa;//throws NPE
}
//it should be like this
@Controller
class A{
@autowired
ServiceImpl simp;
}
@Service
class ServiceImpl{
@Autowired
Adao adoa;
}
@Repository
class Adao{
}