步骤一、新建项目
1. 创建maven项目2. pom.xml3.打印机(普通版)4. 打印机(Spring注解版)
①建立配置类AppConfig,java②在需要创建对象的类前加注解@Component③测试类
注解创建bean对象注解设置bean关系
属性注入
@Autowired 类型注入@Resource name注入 构造器注入(可以替代属性注入)
值注入
@Value 直接注入
步骤 一、新建项目 1. 创建maven项目
只用引入一个spring-context,其余依赖会同时填入。
3.打印机(普通版)org.springframework spring-context 5.3.4
面向接口编程
Ink、Paper接口
相应的实现类ColorInk、BlackInk类 +get方法;A4Paper、A5Paper类+get方法
打印机printer类,包括墨盒ink、纸张paper,有打印方法+setter&getter方法
测试
在Maven程序中,标准的测试程序在text文件夹下
——在pom文件中引入junit,可使用测试注解
——新建同java文件夹下的package(printer)→新建TextPrinter.java
使用Spring创建对象
①建立配置类AppConfig,java@Configuration @ComponentScan(basePackages = " " )
AppConfig.java
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "printer" )//扫描的包
public class AppConfig {
//@Bean标签表示让Spring托管bean
}
@Configuration
public class AppConfig {
//@Bean标签表示让Spring托管bean
@Bean
public SomeBean someBean(){
return new SomeBean();
}
@Bean
public OtherBean otherBean(){
return new OtherBean();
}
}
②在需要创建对象的类前加注解@Component
③测试类
模板
@Test
public void test() {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
SomeBean sb = ctx.getBean(SomeBean.class);
OtherBean ob = ctx.getBean(OtherBean.class);
System.out.println(sb);
System.out.println(ob);
}
注解创建bean对象
读配置文件,进入AppConfig配置文件,找到扫描路径,扫描。此处扫描了package_printer。创建被标记的类的对象。注解设置bean关系 属性注入 @Autowired 类型注入
依赖注入(DI) @Autowired(自动注入)修饰符有三个属性:Constructor,byType,byName。默认按照byType注入。 默认byType注入,前提条件是只能有一个实现类 可以添加@Qualifier选择实现类
将ink与paper注入到printer中
加注解@Autowired后,可以往其中注入对象。通过类型注入。即通过Spring托管的所有bean中,找ink类型的对象注入Ink ink;找paper类型的对象注入Paper paper;。——此时ink类型的对象有BlackInk和ColorInk,默认byType注入,前提条件是只能有一个实现类。故不符合要求。
@Resource默认按byName自动注入。
https://blog.csdn.net/weixin_43072239/article/details/112644511
ink和paper生成构造方法,对构造函数使用@Autowired注解。
值注入不可以使用该方法。
@Value专门用来服务基本类型和String类型。 @Value无法作用于构造方法。



