java – @Import注释的用例是什么?

前端之家收集整理的这篇文章主要介绍了java – @Import注释的用例是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

根据official doc

Annotation Type Configuration

Indicates that a class declares one or more @Bean methods and may be
processed by the Spring container to generate bean definitions…

@Configuration classes may be composed using the @Import annotation,
not unlike the way that works in Spring XML. Because
@Configuration objects are managed as Spring beans within the
container..

但我也可以在没有@Import的情况下使用@Configuration注释.我已经测试了下面列出的代码,它按预期工作.那么使用@Import的目的是什么?

DispatcherServletInitializer

  1. public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
  2. @Override
  3. protected Class

WebMvcConfigurerAdapter

  1. @Configuration
  2. @EnableWebMvc
  3. @ComponentScan(basePackages = { "package.name" })
  4. // @Import(OptionalConfig.class)
  5. public class WebConfig extends WebMvcConfigurerAdapter {
  6. // ...
  7. }

OptionalConfig

  1. @Configuration
  2. public class OptionalConfig {
  3. @Bean(name = "myClass")
  4. public MyClass myClass() {
  5. return new MyClass();
  6. }
  7. }

服务

  1. @Service
  2. public class MyServiceImpl implements MyService {
  3. @Autowired
  4. private MyClass myClass; // yes,it works
  5. // ...
  6. }
最佳答案

Thus far,we’ve seen how to break up bean definitions into multiple @Configuration classes and how to reference those beans across @Configuration boundaries. These scenarios have required providing all @Configuration classes to the constructor of a JavaConfigApplicationContext,and this is not always ideal. Often it is preferable to use an aggregation approach,where one @Configuration class logically imports the bean definitions defined by another.

The @Import annotation provides just this kind of support,and it is the direct equivalent of the element found in Spring beans XML files.

http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch04s03.html

猜你在找的Spring相关文章