Spring 通过注解配置 Bean(2)

来源:互联网 发布:北京市政务数据资源网 编辑:程序博客网 时间:2024/05/20 06:25

Bean 与 Bean 之间的关联关系。 (代码基于上篇文章)

【一】在 Controller 中加上与 Service 的关联关系

@Controllerpublic class UserConntroller {    @Autowired    private UserService userService;    public void execute(){        System.out.println("UserConntroller execute");        userService.add();    }}

【二】在 Service 中加上与 Repository 的关联关系

@Servicepublic class UserService {    @Autowired    private UserRepository userRepository;    public void add() {        System.out.println("UserService add() ");        userRepository.save();    }}

【三】测试类

public class Test {    public static void main(String[] args) {        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");        UserConntroller userConntroller = ctx.getBean(UserConntroller.class);        userConntroller.execute();        /*System.out.println(userConntroller);        UserService userService = ctx.getBean(UserService.class);        System.out.println(userService);        UserRepository userRepository = ctx.getBean(UserRepositoryImpl.class);        System.out.println(userRepository);        TestObject testObject = ctx.getBean(TestObject.class);        System.out.println(testObject);*/    }}

【四】运行结果

2017-12-23 20:25:14 org.springframework.context.support.AbstractApplicationContext prepareRefresh信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5d764be1: startup date [Sat Dec 23 20:25:14 CST 2017]; root of context hierarchy2017-12-23 20:25:14 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions信息: Loading XML bean definitions from class path resource [spring-config.xml]UserConntroller executeUserService add() UserRepositoryImpl save()

代码中用到了 @Autowired 注解,下面来看看它能干什么

<context:component-scan> 元素会自动注册 AutowiredAnnotationBeanPostProcessor 实例, 该实例可以自动装配具有 @Autowired 和 @Resource 、@Inject注解的属性.

使用 @Autowired 自动装配 Bean

@Autowired 注解自动装配具有兼容类型的单个 Bean属性    --> 构造器, 普通字段(即使是非 public), 一切具有参数的方法都可以应用@Authwired 注解    --> 默认情况下, 所有使用 @Authwired 注解的属性都需要被设置. 当 Spring 找不到匹配的 Bean 装配属性时, 会抛出异常, 若某一属性允许不被设置, 可以设置 @Authwired 注解的 required 属性为 false    --> 默认情况下, 当 IOC 容器里存在多个类型兼容的 Bean 时, 通过类型的自动装配将无法工作. 此时可以在 @Qualifier 注解里提供 Bean 的名称. Spring 允许对方法的入参标注 @Qualifiter 已指定注入 Bean 的名称    --> @Authwired 注解也可以应用在数组类型的属性上, 此时 Spring 将会把所有匹配的 Bean 进行自动装配.    --> @Authwired 注解也可以应用在集合属性上, 此时 Spring 读取该集合的类型信息, 然后自动装配所有与之兼容的 Bean.     --> @Authwired 注解用在 java.util.Map 上时, 若该 Map 的键值为 String, 那么 Spring 将自动装配与之 Map 值类型兼容的 Bean, 此时 Bean 的名称作为键值

与 @Autowired 注解的功用类似 的还有 @Resource @Inject

@Resource 注解要求提供一个 Bean 名称的属性,若该属性为空,则自动采用标注处的变量或方法名作为 Bean 的名称@Inject@Autowired 注解一样也是按类型匹配注入的 Bean, 但没有 reqired 属性建议使用 @Autowired 注解
原创粉丝点击