gpt4 book ai didi

Spring:正确设置@ComponentScan

转载 作者:行者123 更新时间:2023-12-04 15:34:57 27 4
gpt4 key购买 nike

我为我的 Spring Application Context 进行了以下设置.


@Configuration
public class RmiContext {
@Bean
public RmiProxyFactoryBean service() {
RmiProxyFactoryBean rmiProxy = new RmiProxyFactoryBean();
rmiProxy.setServiceUrl("rmi://127.0.1.1:1099/Service");
rmiProxy.setServiceInterface(Service.class);
return rmiProxy;
}
}

@Configuration
public class LocalContext {
@Bean
public Controller Controller() {
return new ControllerImpl();
}
}

@Configuration
@Import({RmiContext.class, LocalContext.class})
public class MainContext {



}


上述设置工作正常,但我想启用 @ComponentScan批注 Controller s 与 @Component因为有很多 Controller s 在我的应用程序中使用 @Bean 一一声明时很乏味.

@Configuration
@ComponentScan(basePackageClasses = {Controller.class})
public class LocalContext {
/* ... */
}
问题是当我做 @ComponentScan(basePackageClasses = {Controller.class}) ,以前做工精细 RmiProxyFactoryBean无法识别或无法创建。

那么,如何配置我的 MainContext以便通过 RMI 和本地 bean 创建两个 bean?

最佳答案

@Configuration 也是组件扫描的候选对象,因此您可以通过以下方式扫描 RmiContext 中的所有 bean 和 Controller 包中的所有 Controller :

@Configuration
@ComponentScan(basePackages = {"org.example.controllers", "package.of.RmiContext"})
public class MainContext {
}

- 编辑 -

@Configuration 是组件扫描的候选对象,这是在我的电脑上运行的测试用例:
package scan.controllers;
@Controller
public class ExampleController {
}

package scan;
public interface RMIService {
}

package scan;
@Configuration
public class RmiContext {
@Bean
public RmiProxyFactoryBean service() {
RmiProxyFactoryBean rmiProxy = new RmiProxyFactoryBean();
rmiProxy.setServiceUrl("rmi://127.0.1.1:1099/Service");
rmiProxy.setServiceInterface(RMIService.class);
rmiProxy.setLookupStubOnStartup(false);
return rmiProxy;
}
}

package scan;
@Configuration
//MainContext will auto scan RmiContext in package scan and all controllers in package scan.controllers
@ComponentScan(basePackages = {"scan", "scan.controllers"})
public class MainContext {
}

package scan;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={MainContext.class})
public class TestContext {

@Autowired private RMIService rmi;
@Autowired private ExampleController controller;

@Test
public void test() {
//both controller and rmi service are autowired as expected
assertNotNull(controller);
assertNotNull(rmi);
}
}

关于Spring:正确设置@ComponentScan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17857770/

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