【Spring入门】13.通过注解配置Bean
在 classpath 中扫描组件
组件扫描(component scanning): Spring 能够从 classpath 下自动扫描, 侦测和实例化具有特定注解的组件.
特定组件包括:
@Component:基本注解, 标识了一个受 Spring 管理的组件
@Respository: 标识持久层组件
@Service:标识服务层(业务层)组件
@Controller:标识表现层组件
对于扫描到的组件, Spring 有默认的命名策略:使用非限定类名, 第一个字母小写. 也可以在注解中通过 value 属性值标识组件的名称
例子如下:
一、在src中新建三个包, 类TestObject。每个子包再新建类UserController, UserRepositoryImpl, UserService, 并分别打上标签@Component, @Controller, @Repository, @Service ,其中UserRepositoryImpl实现接口UserRepository。
其中对userRepositoryimpl 添加的注解@Repository的value值是"Repository"以表示Repository即该组件的名称
二、新建xml配置文件,用context:component-scan标签指定Spring IOC要扫描的classpath
注意要在beans标签里用xmlns属性添加context的命名空间,并配置好xsi:schemaLocation
三、新建Main类测试
```
public class Main {
public static void main(String[] args){
ApplicationContext ctx =new ClassPathXmlApplicationContext("beans-annotation.xml");
TestObject to = (TestObject) ctx.getBean("testObject");
System.out.println(to);
UserController userController = (UserController) ctx.getBean("userController");
System.out.println(userController);
UserService userService = (UserService) ctx.getBean("userService");
System.out.println(userService);
UserRepository userRepository = (UserRepository) ctx.getBean("userRepository");
System.out.println(userRepository);
}
}
```
测试结果如图: