Spring:正确设置@ComponentScan

前端之家收集整理的这篇文章主要介绍了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);
    }
}
原文链接:https://www.f2er.com/spring/432251.html

猜你在找的Spring相关文章