IOC操作基于注解方式实现Bean管理功能
------------恢复内容开始------------
基于注解方式实现对象创建与注入属性
(1)注解是代码特殊标记用@注解名称
(2)注解可以作用于类上面、方法上、属性上(可以简化xml配置)
(3)Bean管理中,针对创建对象提供的注解:
(a)@Component :最普通的注解
(b) @Service :用于业务逻辑层(service层)
(c) @Controller :用于web
(d) @Repository :用于dao层(持久层)
*上面四个注解功能一致,都可以创建bean实例,但是为了开发交互,都分的开
基于注解方式实现对象创建的演示:
第一步引入依赖
第二步,开启组件扫描:先修改xml头部
<!--开启组件扫描-->
<!--如果想扫描dao这个类,按照如下,但是如果要扫描多个包加,com.atguigu.Springdemo.service连接-->
<!--或者写扫描包的上层目录com.atguigu.Springdemo-->
<context:component-scan base-package="com.atguigu.Springdemo.dao"></context:component-scan>
第三步,创建类,在类上添加创建对象注解
//在注解里的value属性值可以省略不写,默认值是类名称,首字母小写的名字
@Component(value = "userservice")//这里value与<bean id="userservice" class="....">写法一致
//这里可以更换其他注解Service、Controller、Repository 效果一样
public class user {
public void add()
{
System.out.println("add");
}
}
这里getBean是获取注解里value的值
在测试运行时如果报错java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing
可以试试把@test的jar包导入4.10以下版本
<!--开启组件扫描的其他写法-->
<!--这里use-default-filters的作用是不使用默认的filter,自己配置filter就会不会扫描包中所有
-->
<context:component-scan base-package="com.atguigu" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<!--context:include-filter可以设置扫描哪些内容,type="annotation"表示用注解方式-->
<!--expression表示扫描注解方式为Controller的到package中寻找-->
</context:component-scan>
<!--组件扫描表示方式3-->
<!--下面这种方式扫描包中所有内容
context:exclude-filter这里要与上面区分是exclude不包含,设置哪些内容不进行扫描
当注解方式为Controller的注解不进行扫描
-->
<context:component-scan base-package="com.atguigu">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
------------恢复内容结束------------