Spring:正确设置@ComponentScan

我已经为我的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用@Component注释控制器,因为我的应用程序中有许多控制器,当使用@Bean逐个声明时很乏味.


@Configuration
@ComponentScan(basePackageClasses = {Controller.class})
public class LocalContext {
    /* ... */
}

问题是,当我执行@ComponentScan(basePackageClasses = {Controller.class})时,无法识别或无法创建以前正常工作的RmiProxyfactorybean.

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

最佳答案
@Configuration也是组件扫描的候选者,因此您可以通过以下方式扫描RmiContext中的所有bean以及控制器包中的所有控制器:

@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的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...