定义一下四个类或接口
1. 使用 Spring 注解装配它们
2. 从 BeanFactory 获得一个 PC 实例
3. - usb1 连接鼠标
4. - usb2 连接键盘
工程目录(不需要手动添加依赖)
package com.newer.ioc1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
/**
* 电脑
*/
import org.springframework.stereotype.Component;
@Component
//单例
@Scope("singleton")
public class PC {
// 对象自动分配
@Autowired
// 明确指定
@Qualifier("mouse")
Usb usb1;
@Autowired
@Qualifier("keyboard")
Usb usb2;
void run() {
usb1.work();
usb2.work();
}
}
Usb.java
package com.newer.ioc1;
/*
* Usb接口
*/
import org.springframework.stereotype.Component;
@Component
public interface Usb {
void work();
}
Mouse.java
package com.newer.ioc1;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* 鼠标
*/
import org.springframework.stereotype.Component;
@Component
public class Mouse implements Usb {
@Override
public void work() {
System.out.println(this+"连接鼠标");
}
// 构造后运行
@PostConstruct
public void ready() {
System.out.println("Mouse is Ready!");
}
// 销毁前运行
@PreDestroy
public void destory() {
System.out.println("Mouse is Destory!");
}
}
Keyboard.java
package com.newer.ioc1;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* 键盘
*/
import org.springframework.stereotype.Component;
@Component
public class Keyboard implements Usb {
@Override
public void work() {
System.out.println(this+"连接键盘");
}
// 构造后运行
@PostConstruct
public void ready() {
System.out.println("Keyboard is Ready!");
}
// 销毁前运行
@PreDestroy
public void destory() {
System.out.println("Keyboard is Destory!");
}
}
Ioc1Application.java
package com.newer.ioc1;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Ioc1Application {
public static void main(String[] args) {
SpringApplication.run(Ioc1Application.class, args);
}
// 命令行执行的方法
@Bean
public CommandLineRunner a(BeanFactory beanFactory) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
// 从BeanFactory获得一个PC实例
PC pc=beanFactory.getBean(PC.class);
pc.run();
}
};
}
}
控制台运行:
想要了解Spring IoC的小伙伴可以去前面的博客看看,欢迎有问题的留言!!!