有@Autowired、@Resource了是否还需要xml配置?

@Resource是属于J2EE的,默认安照“名称”进行装配;

@Autowired是属业spring的,默认按“类型”装配;

Java bean注入的写法演变:

1.-----------------------------------------------------xml配置+变量声明+set/get方法

2.spring没有配置查找bean的文件目录:xml配置+变量声明+spring标签

3.spring配置了查找bean的文件目录:-----------------变量声明+spring标签

-------------------------------------------------------------------------------------------------

但难点是谁知道spring有没有配置bean的默认目录,我以前用的项目配置了默认的文件,所以一直觉得写了spring 标签后可以不用xml配置,结果出现如下错误,只好进行xml文件bean配置。

刚查了下发现spring的bean扫描目录配置可能如下:

< context:component-scan base-package="com.baobaotao" resource-pattern="anno/*.class"/ >
可通过context命名空间的component-scan的base-package属性指定一个需要扫描的基类包,Spring容器将会扫描这个基类包里的所有类,并从类的注解信息中获取Bean的定义信息。

这里我们将基类包设置为com.baobaotao,默认情况下resource-pattern属性的值为"**/*.class",即基类包里的所有类。这里我们设置为"anno/*.class",则Spring仅会扫描基包里anno子包中的类。





-------------------------------------------------------------------------------------------------------------------------------

@Autowired

可以自动帮你把bean里面引用的对象的setter/getter方法省略,它会自动帮你set/get

@resource

也是可以省略

setter/getter方法的,但如果省略了

@resource的name属性,理论上说

name值默认与所标注变量名相同,但我实际应用中报“XXX is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?”,~~~~~~写了name属性照样报这个错~~~~~~




猜你喜欢

转载自blog.csdn.net/jim_007/article/details/79095072
今日推荐