微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐