码迷,mamicode.com
首页 > 编程语言 > 详细

spring 注解实现自动装配

时间:2020-07-19 00:44:39      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:bbb   ref   ase   package   pack   http   version   col   官网   

官网:https://docs.spring.io/spring/docs/5.2.7.RELEASE/spring-framework-reference/core.html#beans-annotation-config

1、导入约束

2、配置注解支持

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

</beans>

1、pojo

person.java

package com.wt.pojo;


import org.springframework.beans.factory.annotation.Autowired;

public class Person {
    private String name;
    @Autowired
    private Dog dog;
    @Autowired
    private Cat cat;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }
}

2、xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

<bean id="cat" class="com.wt.pojo.Cat"/>
<bean id="dog" class="com.wt.pojo.Dog"/>
    <bean id="person" class="com.wt.pojo.Person" name="per">
        <property name="name" value="win"/>
    </bean>

</beans>

如果@Autowrited自动装配的环境比较复杂,自动装配无法通过一个注解 @Autowrited 完成的时候

使用@Qualifier(value = "xx")配合使用

spring 注解实现自动装配

标签:bbb   ref   ase   package   pack   http   version   col   官网   

原文地址:https://www.cnblogs.com/wt7018/p/13337984.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!