@Autowired依赖注入

package com.springboot.chapter3.pojo;

import com.springboot.chapter3.pojo.definition.Animal;
import com.springboot.chapter3.pojo.definition.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BussinessPerson implements Person {

    @Autowired//首先根据类型找到对应的Bean,如果对应类型的Bean不是唯一的,那么它会根据其属性名称和Bean的名称进行匹配,如果无法匹配就会抛出异常
    //@Autowired如果不能确定其标注属性一定会存在并且允许这个被标注的属性为null
    private Animal cat = null;

    @Override
    public void Service() {
        this.cat.use();
    }

    @Override
    public void setAnimal(Animal animal) {
        this.cat=animal;
    }
}
package com.springboot.chapter3.pojo;

import com.springboot.chapter3.pojo.definition.Animal;
import org.springframework.stereotype.Component;

@Component
public class Cat implements Animal {
    @Override
    public void use() {
        System.out.println("猫【"+ Cat.class.getSimpleName()+"】是抓老鼠用的");
    }
}
package com.springboot.chapter3.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.springboot.chapter3.*") //定义扫描的包
public class AppConfig {

}
package com.springboot.chapter3.config;

import com.springboot.chapter3.pojo.BussinessPerson;
import com.springboot.chapter3.pojo.definition.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.logging.Logger;

public class IoCTest {
    private static Logger log = Logger.getLogger(String.valueOf(IoCTest.class));

    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
        Person person = ctx.getBean(BussinessPerson.class);
        person.Service();
    }
}
posted @ 2020-04-11 11:03  xl4ng  阅读(494)  评论(0编辑  收藏  举报