Spring中对象是null的解决方案

本文探讨了在使用Spring框架通过XML配置文件注入Bean实例时遇到的问题,即Bean实例被注入为null的情况。作者尝试了多种方法最终通过在Action类中使用@Autowired注解解决了问题。

今天在使用spring注入bean实例的时候,不知道为什么注入的是null,百度了好久也找不到答案,问一个同学他给我发来了一篇博文是用的@Autowired注解,但是我并没有使用注解,而是使用的普通的xml文件方式来注入,但是注入的是null,搞得我头大。

参考博文地址:https://blog.youkuaiyun.com/qq_32623363/article/details/80666942

1. application.xml文件我是这样写的

<bean id="customerDAO" class="com.myshop.dao.CustomerDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="customerService" class="com.myshop.service.CustomerService">
<property name="customerDAO">
<ref bean="customerDAO" />
</property>
</bean>
<bean id="customerAction" class="com.myshop.action.CustomerAction">
<property name="customerService">
<ref bean="customerService" />
</property>

</bean>

2. Action类部分代码:

private CustomerService customerService;

        public  CustomerService getCustomerService() {
return customerService;
}
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;

}

就这样,注入的customerServie是null,不知道为什么

3. 后来将action类中代码修改为:仅仅是增加了static

@Autowired

private static CustomerService customerService;

public static CustomerService getCustomerService() {
return customerService;
}
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;

}

这样就好了,不知道为什么,有知道大神可以告诉我不

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值