首页 > java main方法中通过ApplicationContext去拿bean(用注解的bean)getbean拿不到?

java main方法中通过ApplicationContext去拿bean(用注解的bean)getbean拿不到?

java main方法中通过ApplicationContext去拿bean(用注解的bean)getbean拿不到?
注解类代码如下:

ApplicatonContext.xml配置如下:


main方法如下:

上面注释的是普通main方法,下面是junit测试,都拿不到。
如果userService通过xml配置在ApplicationContext中配置,这样是可以拿到的。


XML文件错了,没有你这种写法。

XML里直接写上<context:component-scan base-package="com.springaop" />就行,去掉<context:annotation-config> </context:annotation-config>


base-package里面的包写成com.springoop.*试试看


你的工程中两个配置文件,搞清用的哪个,确保spring加载的正常,控制台会有输出的,不会拿不到的


配置文件不对,没有将bean注入进来啊。多贴点而配置文件出来看看。


用spring boot吧


junit里的代码有没有写对,需要手动去触发初始化, 写在before注解下。

public class EnterSearchServiceTest {
    private IEnterService enterService; 
           
    @Before
     public void init() {         
      ApplicationContext aCtx 
          = new FileSystemXmlApplicationContext(
                  new String[]{"classpath:applicationContext.xml"
             ,"classpath:mybatis-config.xml"});
       
      IEnterService service = (IEnterService) aCtx.getBean("EnterService");            
      this.enterService = service;
     }
【热门文章】
【热门文章】