加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 01:25:09 所属栏目:大数据 来源:网络整理
导读:根据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 a

根据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

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class

WebMvcConfigurerAdapter

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "package.name" })
// @Import(OptionalConfig.class) 
public class WebConfig extends WebMvcConfigurerAdapter {
    // ...
}

OptionalConfig

@Configuration
public class OptionalConfig {

    @Bean(name = "myClass")
    public MyClass myClass() {
        return new MyClass();
    }
}

服务

@Service
public class MyServiceImpl implements MyService {

    @Autowired
    private MyClass myClass;    // yes,it works

    // ...
}
最佳答案

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读