spring中使用@Autowired报空指针

J2EE 码拜 9年前 (2015-04-06) 3410次浏览 0个评论

蜗牛一般的小菜刚刚接触spring,今天刚弄懂@componet注解,是扫描直接注入的,不需要在配置文件中加<bean id…,但是想到如果这个实体需要参数的话,还是要在配置文件中配的啊,之前只用过<bean id=*** autowire=”byName”>的自动装配,今天想起了@Autowired,心里觉得这么个小实验,结果竟然报空指针,各位看官大拿,走过路过不要错过啊~~欢迎拍砖
1.Car类:
public class Car {
private String carName;
private String carNo;
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public String getCarNo() {
return carNo;
}
public void setCarNo(String carNo) {
this.carNo = carNo;
}
}

spring中使用@Autowired报空指针
2.Boss类(用到了@Autowired注解
public class Boss {
@Autowired
private Car car;
public String toString(){
return “Big Boss is driving a “+car.getCarName()
+”, car Number is “+car.getCarNo();
}
}
spring中使用@Autowired报空指针
3.bean 配置文件:
<bean
class=”org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor” />
<bean id=”boss” class=”annota.wire.Boss”></bean>
<bean id=”car” class=”annota.wire.Car”>
<property name=”carName” value=”Benz”></property>
<property name=”carNo” value=”5210″></property>
</bean>
spring中使用@Autowired报空指针
4.用来测试的main函数(报空指针,debug的时候发现boss实例里的car为null):
public static void main(String[] arge){
BeanFactory bf=new XmlBeanFactory(new ClassPathResource(“beans.xml”));
Boss boss=(Boss)bf.getBean(“boss”);
System.out.println(boss);
}
spring中使用@Autowired报空指针
	<!-- 需要扫描的标注了@Controller的类 -->
	<context:component-scan base-package="com.mine">
		<context:include-filter type="regex"
			expression=".*.*.action.*" />
			<!-- 这里排除service,防止事务失效 -->
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> 
	</context:component-scan>

类似于这样,去配置一个自动扫描

spring中使用@Autowired报空指针
40分
我们这都是
@Autowired
@Qualifier(“signupTestMapper”)
SignupTestMapper signupTestMapper;

也可以用@Resource
至于为什么,真不知道。。。。

spring中使用@Autowired报空指针
引用 4 楼 shijing266 的回复:
	<!-- 需要扫描的标注了@Controller的类 -->
	<context:component-scan base-package="com.mine">
		<context:include-filter type="regex"
			expression=".*.*.action.*" />
			<!-- 这里排除service,防止事务失效 -->
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> 
	</context:component-scan>

类似于这样,去配置一个自动扫描

已经加了

<context:annotation-config />

	<context:component-scan base-package="annota.wire" />

这两句,不好使啊,而且:“
如果扫描到有@Component @Controller@Service等这些注解的类,则把这些类注册为bean”
我只是用到了@Autowire的注解,是需要用已注册的bean赋值给被注解的域成员的啊,不是要将这个域成员注册成bean,这个自动扫描的意义在哪里呢,是不是我哪理解错了

spring中使用@Autowired报空指针
引用 5 楼 u010880076 的回复:

我们这都是
@Autowired
@Qualifier(“signupTestMapper”)
SignupTestMapper signupTestMapper;

也可以用@Resource
至于为什么,真不知道。。。。

正解!
撒花ing!
下面是我在ITeye里搜到的,后面再慢慢加深体会吧,共勉!

@Qualifier(“XXX”) 中的 XX是 Bean 的名称,所以 @Autowired 和 @Qualifier 结合使用时,自动注入的策略就从 byType 转变成 byName 了。


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明spring中使用@Autowired报空指针
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!