一、注册bean的方式
向Spring容器中注册bean通常有以下几种方式:
1. 包扫描+给组件标注注解(@Controller、@Servcie、@Repository、@Component),但这种方式比较有局限性,局限于我们自己写的类
2. @Bean注解,通常用于导入第三方包中的组件
3. @Import注解,快速向Spring容器中导入一个组件
二、简单介绍@Import导入组件
通过@Import(xxx.class)给容器中自动创建出这个类型的组件、默认组件的名字就是全类名
2.1 没有使用@Import注解时的效果
首先,我们创建一个Color类,这个类是一个空类,没有成员变量和方法,如下所示:
package com.tianxia.springannotation.entity;
public class Color {
}
然后,创建测试方法,输出Spring容器中所有bean定义的名字,来查看是否存在Color类对应的bean实例,以此来判断Spring容器中是否注册有Color类对应的bean实例。
/**
* 测试Import
*/
@Test
public void testImport() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig02.class);
String[] definitionNames = applicationContext.getBeanDefinitionNames();
for (String name : definitionNames) {
System.out.println(name);
}
}
输出的结果信息如下所示:
可以看到Spring容器中并没有Color类对应的bean实例。
2.2.使用@Import注解时的效果
配置类上添加一个@Import注解,并将Color类填写到该注解中
package com.tianxia.springannotation.config;
import com.tianxia.springannotation.config.configEntity.CustomerScope;
import com.tianxia.springannotation.entity.Color;
import com.tianxia.springannotation.entity.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Scope;
/**
* 配置类
**/
@Configuration
@Import(Color.class)
public class MainConfig03 {
/**
* 创建person实例
* @return
*/
@Bean("person03")
@Scope(CustomerScope.CUSTOMER_SCOPE)
public Person person() {
System.out.println("给容器中添加咱们这个Person对象...");
return new Person("liqb", 24);
}
}
运行测试方法,输出的结果信息如下所示:
使用@Import注解快速地导入组件时,容器中就会自动注册这个组件,并且id默认是组件的全类名。
三、@Import注解还支持同时导入多个类
格式如下:
@Import({xxx.class, xxx.class})
举例:
@Import({Color.class, Red.class})
四、@Import注解可以用在以下几个位置
4.1 在配置类中使用
可以在一个配置类上使用@Import
注解,将其他配置类导入其中。这样可以将多个配置类聚合在一起,形成一个更大的配置类。例如:
@Configuration
@Import(OtherConfig.class)
public class MyConfig {
// 配置信息...
}
4.2 在组件类中使用
可以在一个组件类上使用@Import
注解,将其他组件类导入其中。这样可以将多个组件类集中管理,统一进行配置。例如:
@Component
@Import(OtherComponent.class)
public class MyComponent {
// 组件代码...
}
4.3 在启动类中使用
可以在启动类上使用@Import
注解,将其他配置类或组件类导入其中。这样可以将各个配置类或组件类集中管理,统一进行启动配置。例如:
@SpringBootApplication
@Import({ConfigOne.class, ConfigTwo.class, MyComponent.class})
public class MyApp {
// 启动代码...
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
总的来说,@Import
注解可以用在任何类上(该类需要交由spring管理),用于将其他配置类或组件类导入其中,并统一进行管理和配置。这样可以提高代码的模块化和可维护性。