@Import may be introduced bean or @Configuration modified configuration class. If a standard class configuration springboot the packet structure, is SpringbootApplication start at the root of the class package, configuration, in sub-packets. You do not need to use @Import import the configuration class, if configured in the class of third-party jar down, we want to introduce this configuration class, we need to @Import its introduction to the project to take effect. Because this time configuration class no longer springboot within the default scan range.
Further, @Import equivalent Spring xml configuration file <import /> tag.
Here's a look at @Import several usage:
Use a method: introducing the general category
1.1 with a normal class @Import after introduction into a the bean . This class does not use @Service , @Component to create it as bean .
@Getter @Setter public class MySqlConn { private String driverClass = "xxxx"; private String url = "jdbc:mysql://localhost:3306/mydb"; private String userName = "root"; private String password = "root"; }
1.2 springboot start classes @Import this class that can be used as other types of bean to reference.
@SpringBootApplication @Import({MySqlConn.class}) public class SpringBootApplication1 { public static void main(String[] args) { SpringApplication.run(SpringBootApplication1.class, args); } }
1.3 test, the definition of a controller to test this by calling @Import import manner bean
@RestController @RequestMapping("test") public class RestTestController { @Autowired private MySqlConn mySqlConn; @GetMapping("common") public String commonBean() { String jsonResult = ""; ObjectMapper mapper = new ObjectMapper(); try { jsonResult = mapper.writeValueAsString(mySqlConn); } catch (JsonProcessingException e) { e.printStackTrace(); } return jsonResult; } }
Use two: and @Configuration with the use of
@Import be used to integrate @Configuration annotation defined bean configuration.
2.1 class defines a configuration @Configuration , configuration class defines a number of the bean . The following code can be seen in our definition of bean is MySqlServerBean .
@Configuration public class MySqlConfig { @Bean public MySqlServerBean getBean() { MySqlServerBean bean = new MySqlServerBean(); bean.setUserName("lyj"); return bean; } }
2.2 startup class @import this configuration categories:
@SpringBootApplication @Import(MySqlConfig.class) public class SpringBootApplication3 { public static void main(String[] args) { SpringApplication.run(SpringBootApplication3.class, args); } }
2.3 test, the definition of a controller, we see the controller in can be used directly in MySqlConfig defined MySqlServerBean up.
@RestController @RequestMapping("test") public class RestTestController { @Autowired private MySqlServerBean mySqlServerBean; @GetMapping("mysql") public String mysql() { String jsonResult = ""; ObjectMapper mapper = new ObjectMapper(); try { jsonResult = mapper.writeValueAsString(mySqlServerBean); } catch (JsonProcessingException e) { e.printStackTrace(); } return jsonResult; } }
Use Method three: introducing in the configuration class
Classes in the configuration @Import directly into classes, may be cited as the bean .
3.1 class definition of a common
@Getter @Setter public class PoolBean { private String redisHost = "127.0.0.1"; private String redisPort = "6379"; private String redisDb = "0"; }
3.2 import this class in the configuration class
@Configuration @Import({PoolBean.class}) public class RedisConfig { @Bean public RedisClusterBean getHost() { return new RedisClusterBean(); } }
3.3 Test to start the project in the controller direct reference to this PoolBean .
@SpringBootApplication public class SpringBootApplication2 { public static void main(String[] args) { SpringApplication.run(SpringBootApplication2.class, args); } }
@RestController @RequestMapping("test") public class RestTestController { @Autowired private PoolBean poolBean; @GetMapping("pool") public String poolBean() { String jsonResult = ""; ObjectMapper mapper = new ObjectMapper(); try { jsonResult = mapper.writeValueAsString(poolBean); } catch (JsonProcessingException e) { e.printStackTrace(); } return jsonResult; } }
Use four: and with the use of ImportSelector
Create a Maven project, pom.xml type that jar , we write a third party jar package, used to refer to our main project, carried out ImportSelector example of use. Probably engineering structures below:
4.1 In the third-part feature, we first define a config
@Configuration public class AppConfig { @Bean public Student studentBean() { Student student = new Student(); student.setId(10); student.setName("王某"); return student; } }
4.2 Customizing a SpringStartSelector implement an interface ImportSelector , the BeanFactoryAware . Rewriting selectImports () method and setBeanFactory () method. Here is first run when the program starts setBeanFactory () method, we can get into here beanFactory . selectImports () method back to the AppCoinfig full class name.
public class SpringStartSelector implements ImportSelector, BeanFactoryAware { private BeanFactory beanFactory; @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { System.out.println("importingClassMetaData:" + importingClassMetadata); System.out.println("beanFactory:" + beanFactory); return new String[]{AppConfig.class.getName()}; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } }
4.3 a custom annotations EnableSpringStudy , used in this annotation @Import () introduced into customized 4.2 SpringStartSelector
@Retention(RetentionPolicy.RUNTIME) @Documented @Target(ElementType.TYPE) @Import(SpringStartSelector.class) public @interface EnableSpringStudy { }
4.4 After the completion of our third-part project labeled jar package, the main project of pom introduced file
<dependency> <groupId>com.win.world</groupId> <artifactId>third-part</artifactId> <version>1.0.0</version> </dependency>
4.5 Main projects in SpringBoot our 4.3 custom annotations on start classes. Then we can get to test AppConig the bean .
@SpringBootApplication @EnableSpringStudy public class SpringBootApplication4 { public static void main(String[] args) { SpringApplication.run(SpringBootApplication4.class, args); } }
To test whether past AppConfig the bean
@RestController @RequestMapping("test") public class RestTestController { @Autowired private Student student; @GetMapping("selector") public String selector() { String jsonResult = ""; ObjectMapper mapper = new ObjectMapper(); try { jsonResult = mapper.writeValueAsString(student); } catch (JsonProcessingException e) { e.printStackTrace(); } return jsonResult; } }
Use five: and with the use of ImportBeanDefinitionRegistrar
ImportBeanDefinitionRegistrar interface is also Spring one extension point, it can support code to write our own packaged as BeanDefinition objects; class that implements this interface callback postProcessBeanDefinitionRegistry methods, registered to Spring container. The bean poured into Spring container there is more than @Service @Component other annotation mode, this interface may also be implemented. The following look at an example:
5.1 We first define a MyImportBeanDefinitionRegistrar class implements ImportBeanDefinitionRegistrar interface, and by rewriting registerBeanDefinitions () to define a bean
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar{ @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { BeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClassName(PoolBean.class.getName()); MutablePropertyValues property = beanDefinition.getPropertyValues(); property.addPropertyValue("redisHost", "localhost"); property.addPropertyValue("redisPort", "6377"); //这里注册bean registry.registerBeanDefinition("poolBean", beanDefinition); } }
5.2 class defines a configuration, @Import import the custom class 5.1
@Configuration @Import(MyImportBeanDefinitionRegistrar.class) public class RegistrarConfig { }
5.3 start the project and test yourself in registerBeanDefinitions () method to create the bean PoolBean success
@SpringBootApplication public class SpringBootApplication5 { public static void main(String[] args) { SpringApplication.run(SpringBootApplication5.class, args); } }
@RestController @RequestMapping("test") public class RestTestController { @Autowired private PoolBean poolBean; @GetMapping("registrar") public String registrarTest() { String jsonResult = ""; ObjectMapper mapper = new ObjectMapper(); try { jsonResult = mapper.writeValueAsString(poolBean); } catch (JsonProcessingException e) { e.printStackTrace(); } return jsonResult; } }
reference:
[1] Spring framework @Import notes, https://segmentfault.com/a/1190000011068471
[2] @Import notes - Import resources, https://blog.csdn.net/u010502101/article/details/78760032
[3] one minute to learn Spring Annotations of @Import notes, https://blog.51cto.com/4247649/2118354
[4] @ Import, ImportSelector notes and use source code analysis, https://juejin.im/post/5d63b455f265da03e52341d0
[5] in-depth understanding of Spring's ImportSelector interfaces, https://www.cnblogs.com/niechen/p/9262452.html
【6】 ImportBeanDefinitionRegistrar, https://blog.csdn.net/baidu_19473529/article/details/90613661