当前位置: 代码迷 >> Java Web开发 >> 通过web.xml实例化后的bean,在类中进行调用报空指针。帮看看,谢谢
  详细解决方案

通过web.xml实例化后的bean,在类中进行调用报空指针。帮看看,谢谢

热度:102   发布时间:2016-04-14 20:47:20.0
通过web.xml实例化后的bean,在类中进行调用报空指针。帮看看,多谢。
web.xml增加了该bean的实例:
<bean id="busrDao" class="pkg.BuserDaoImpl">
<property name="osessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="busrService" class="pkg.BuserServiceImpl">
<property name="busrDao" ref="busrDao"></property>
</bean>
在类中增加了个成员,如下:
public class BuserAct extends ActionSupport {
private BuserService busrService;
public String login() {
try {
BuserAction bu = busrService.login(busr);
类中的login方法通过调用busrService的方法空指针异常,看了下就是busrService为null,请帮忙看看是什么原因?多谢。


------解决思路----------------------
注入失败?
busrService不是@autowired的话,就需要getter/setter了
是从spring容器中无法获取对象
我也是才学……错了请轻拍~
------解决思路----------------------
不是没有autowired么?
还有这个BuserAct有在xml里面定义不..
没有的话要加@Controller什么的和扫包的定义
------解决思路----------------------
你没有用注解的方式吗 ? 那就应该先加载配置文件,然后在通过拿到的对象
StudentDao studentDao = (StudentDao) context.getBean("studentDaoImpl");再使用,
如果使用了注解就 直接在private BuserService busrService;头上加@Resource(name="busrService")
------解决思路----------------------
引用:
Quote: 引用:

不是没有autowired么?
还有这个BuserAct有在xml里面定义不..
没有的话要加@Controller什么的和扫包的定义


--你好,我通过加载手工加载配置文件、然后getbean的方式是可以的。这是不是说我配置的bean应该是没有问题,但怎么能加载到web容器中,后面我直接使用这些实例化的bean呢?

我意思是service跟dao配置了然后要在BuserAct里面的service上面加@Autowired注释
不然不会自动注入的
或者就是在xml里面配置BuserAct这个bean把service那个用property注入进去
不然还是空的
------解决思路----------------------
你的问题不是dao没注进service,而是service没注进action。
LZ使用非注解的话需要在applicationContext.xml中定义的action的bean,而且需要在action中添加对应service的get/set,其他地方也要对应适配。
<bean id="buserAct " class="..." scope="prototype" >
        <property name="busrService" ref="busrService"/>
  </bean>  

------解决思路----------------------
引用:
web.xml增加了该bean的实例:
<bean id="busrDao" class="pkg.BuserDaoImpl">
<property name="osessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="busrService" class="pkg.BuserServiceImpl">
<property name="busrDao" ref="busrDao"></property>
</bean>
在类中增加了个成员,如下:
public class BuserAct extends ActionSupport {
private BuserService busrService;
public String login() {
try {
BuserAction bu = busrService.login(busr);
类中的login方法通过调用busrService的方法空指针异常,看了下就是busrService为null,请帮忙看看是什么原因?多谢。

3种方式:
一、在busrService上添加Resource注解
二、在busrService上添加Autowired注解
三、在xml中配置BuserAct,并且在该类上添加Controller注解
<bean id="busrAct" class="pkg.BuserAct ">
<property name="busrService" ref="busrService"></property>
</bean>

------解决思路----------------------

<property name="osessionFactory" ref="sessionFactory"></propert
改成。。。。
<property name="sessionFactory" ref="sessionFactory"></property>


------解决思路----------------------
@Resource(name="busrService");
private BuserServiceInterface buserService;

private BuserEntity buser;

------解决思路----------------------
private BuserService busrService;
这一个类没有注入,所以你在点他的方法的时候报空指针,在bean里面注入一下就好了。
  相关解决方案