Spring自动装配中用到的几个注解:
组件扫描:
①@Component:表示这个类需要在应用程序中被创建
②@ComponentScan:自动发现应用程序中创建的类
自动装配:
①@Autowired:自动满足bean之间的依赖关系
定义装配类:
①Configuration:表示当前类是一个配置类
下面我们通过代码来展示(需要引入Spring框架):
我使用的maven配置的,maven配置信息如下:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.19.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
接下来是代码:
①定义一个类,假装实现播放音乐的功能,即CD
import org.springframework.stereotype.Component;
@Component
public class CompactDisc {
public CompactDisc() {
System.out.println("CompactDisc无参构造函数");
}
public void play(){
System.out.println("正在播放音乐");
}
}
②定义一个类,假装是音乐播放机
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class CDPlayer {
private CompactDisc cd;
public CDPlayer() {
System.out.println("CDPlayer无参构造");
}
@Autowired
public CDPlayer(CompactDisc cd) {
this.cd = cd;
System.out.println("CDPlayer的有参构造函数");
}
public void play(){
cd.play();
}
}
③定义一个类,用来管理之前的类,就是一个IOC容器
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class AppConfig {
}
④调用
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
CDPlayer player = context.getBean(CDPlayer.class);
player.play();
}
}
其中@Component注解会被Spring自动创建,即创建对象,@ComponentScan可以扫描创建了的类,@Autowired可以自动将bean之间的依赖关系创建,@Configuration表示是一个配置类。
我们来理解一下自动装配@Autowired,在定义的Power、CompactDisc、CDPlayer中,Power和CompactDisc不需要在其中自动装配,只需要被创建出对象即可,所以使用了@Component。在CDPlayer中,我们需要调用Power和CompactDisc对象,按照传统写法,我们需要new对象出来,但是使用Spring后,我们只需要装配(依赖注入)就行。在创建Power和CompactDisc的时候,Spring已经创建了对象并放在容器中,所以在CDPlayer中,我们只需要调用即可,但是要调用的话,我们需要找出这两个对象,此时就是装配了,使用@Autowired就可以装配进来,也就是所谓的依赖注入,因为CDPlayer的运行依赖Power和CompactDisc这两个对象。而AppTest(即测试类)中要测试的话,又需要使用到CDPlayer这个对象,这个对象也已经由Spring创建出来了,此时就只需要调用即可,要调用就需要找到其,找到的方法就是依赖注入,Spring中使用@Autowired即可。