Spring @ComponentScan注释不起作用

时间:2016-02-21 04:25:36

标签: java spring spring-java-config spring-mongodb component-scan

我有包装布局的春季启动应用程序示例:

main:
-com.foo
     Application.java       
-com.foo.services
      ItemService.java
      ItemRepository.java    
-com.foo.config
     Configuration.java
test:
-com.foo.services 
     ItemServiceIngegrationTest.java

我的集成测试无法运行,无法找到ItemRepository bean 如果放

  @ComponentScan(basePackageClasses = { ItemService.class })

但如果我把

起作用
  @ComponentScan(basePackageClasses = { Application.class })

诀窍在哪里?

规范说:

  

basePackageClasses()或basePackages()(或其别名value())   可以指定定义要扫描的特定包。如果具体   包没有定义,扫描将从包中发生   声明此注释的类。

@EnableAutoConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { Configuration.class })
public class ItemServiceIntegrationTest { 
    . . .
}

@org.springframework.context.annotation.Configuration
@PropertySource("classpath:application.properties")
@ComponentScan(basePackageClasses = { ItemService.class })
public class Configuration extends AbstractMongoConfiguration {
   .  .  .
}   

1 个答案:

答案 0 :(得分:2)

javadoc说:

  

如果未定义特定包,则将从声明此批注的类的包进行扫描。

因此,它会从声明@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTabHost = (FragmentTabHost) findViewById(R.id.tabhost); mTabHost.setup(this, getSupportFragmentManager(), R.id.fake_frame); mTabHost.addTab(mTabHost.newTabSpec(POPULAR).setIndicator(POPULAR), MovieListFragment.class, null); mTabHost.addTab(mTabHost.newTabSpec(HIGHEST_RATED).setIndicator(HIGHEST_RATED), MovieListFragment.class, null); mTabHost.addTab(mTabHost.newTabSpec(FAVOURITE).setIndicator(FAVOURITE), MovieListFragment.class, null); //We check if the layout selected has two fragments if (findViewById(R.id.movie_detail_container) != null) { //If it has two, we update our member variable mTwoPane = true; /*If the activity has been recently created, we replace the placeholder frameview with the actual detail fragment */ if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .replace( R.id.movie_detail_container, new DetailActivityFragment(), DETAIL_TAG ).commit(); } } else { mTwoPane = false; } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } 的包中进行扫描,除非定义了特定的包类。你能把它放在ComponentScan班吗?