gpt4 book ai didi

java - @Import 注解的用例是什么?

转载 作者:IT老高 更新时间:2023-10-28 13:44:47 26 4
gpt4 key购买 nike

根据official doc :

Annotation Type Configuration

Indicates that a class declares one or more @Bean methods and may beprocessed 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 thecontainer..

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

DispatcherServletInitializer

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { WebConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}

@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}

}

WebMvcConfigurerAdapter

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

可选配置

@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

// ...
}

最佳答案

如果启用组件扫描,您可以在多个@Configuration 类中拆分bean 定义,而无需使用@Import。而且您不需要将所有这些都提供给应用程序上下文构造函数。

我认为 @Import 的主要目的是 如果您想避免组件扫描(从 Spring Framework 4.2 开始,根据引用),为您提供一种简化多个配置注册的方法手册)。

Spring Reference Documentation about @Import usage: 中有一条注释

As of Spring Framework 4.2, @Import also supports references to regular component classes, analogous to the AnnotationConfigApplicationContext.register method. This is particularly useful if you’d like to avoid component scanning, using a few configuration classes as entry points for explicitly defining all your components.

关于java - @Import 注解的用例是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35502164/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com