加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Spring:正确设置@ComponentScan

发布时间:2020-12-15 01:30:02 所属栏目:大数据 来源:网络整理
导读:我已经为我的Spring Application Context设置了以下内容. @Configurationpublic class RmiContext {@Bean public RmiProxyFactoryBean service() { RmiProxyFactoryBean rmiProxy = new RmiProxyFactoryBean(); rmiProxy.setServiceUrl("rmi://127.0.1.1:109

我已经为我的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);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读