基于注解方式配置bean
基于注解方式配置bean
● 基本介绍
基于注解的方式配置 bean, 主要是项目开发中的组件,比如 Controller、Service、和 Dao.
● 组件注解的形式有
1. @Component 表示当前注解标识的是一个组件
2. @Controller 表示当前注解标识的是一个控制器,通常用于 Servlet
3. @Service 表示当前注解标识的是一个处理业务逻辑的类,通常用于 Service 类
4. @Repository 表示当前注解标识的是一个持久化层的类,通常用于 Dao 类
● 代码实现
1. 引入 spring-aop-5.3.8.jar , 在 spring/libs 下拷贝即可
创建 UserAction.java UserService.java, UserDao.java MyComponent.java




配置xml文件
<!-- 配置自动扫描的包,注意需要加入 context 名称空间 --> <!--注意事项: 1.如果想扫描一个大包下的多个子包可以使用通配符*,如com.recorder.spring.* 2.配置的包会扫描这个包下的类以及这个包下的子包的类(带注解的) 3. Spring 的 IOC 容器不能检测一个使用了@Controller 注解的类到底是不是一个真正的控制器。 注解的名称是用于程序员自己识别当前标识的是什么组件。其它的@Service @Repository 等 也是一样的道理 [也就是说 spring 的 IOC 容器只要检查到注解就会生成对象, 但是这个注解的含义 spring 不会识别,注解是给程序员编程方便看的] 4.resource-pattern="User*.class": 表示只扫描满足要求的类(User开头的).[使用的少,不想扫描,不写注解就可以, 知道这个知识点即可]
这里因为是用的是out目录下面的.class文件
5.排除哪些类 , 以 annotaion 注解为例: <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> 解读 :1) <context:exclude-filter> 放在<context:component-scan>内,表示扫描过滤掉当前包的某些类 2) type="annotation" 按照注解类型进行过滤 3) expression :就是注解的全类名,比如 org.springframework.stereotype.Service 就是 @Service 注解的全类名,@Controller/@Repository等依次类推 4) 上面表示过滤掉 com.recorder.spring.component包下,所有加入了@Service 注解的类--> <!--<context:component-scan base-package="com.recorder.spring.component">--> <!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>--> <!--</context:component-scan> 6. 指定自动扫描哪些注解类 解读 1) use-default-filters="false": 不再使用默认的过滤机制 2) context:include-filter: 表示只是扫描指定的注解的类 3) expression="org.springframework.stereotype.Controller": 注解的全类名 --> <!--<context:component-scan base-package="com.recorder.spring.component" use-default-filters="false">--> <!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>--> <!--</context:component-scan>--> <context:component-scan base-package="com.recorder.spring.component"/>
测试
@Test //通过自动装配获取bean public void setBeanByAutoWire() { //创建一个容器,并和配置文件关联(一个容器关联一个配置文件) ApplicationContext ioc = new ClassPathXmlApplicationContext("beans.xml"); OrderAction orderAction = ioc.getBean("orderAction", OrderAction.class); System.out.println(orderAction.getOrderService()); System.out.println(orderAction.getOrderService().getOrderDao()); }

本文来自博客园,作者:紫英626,转载请注明原文链接:https://www.cnblogs.com/recorderM/p/16808151.html

浙公网安备 33010602011771号