Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 定义ApplicationContext.xml后,如何访问bean_Java_Spring - Fatal编程技术网

Java 定义ApplicationContext.xml后,如何访问bean

Java 定义ApplicationContext.xml后,如何访问bean,java,spring,Java,Spring,我使用ApplicationContext访问我的bean,如下所示: ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate"); 现在我想创建一个ap

我使用ApplicationContext访问我的bean,如下所示:

ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");
 StudentJDBCTemplate studentJDBCTemplate = 
      (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
现在我想创建一个applicationContext.xml,在这里我使用组件扫描,如下所示:

<context:component-scan base-package="org.manager.*" />

这样我就不必创建ApplicationContext对象来访问bean,并将其放在我的WEB-INF文件夹下,如前所述


我的问题是,我现在如何访问我的bean?因为现在没有ApplicationContext对象可供我使用

您可以使用@Autowired注释。为此

  • 添加到applicationContext.xml中,以便启用注释驱动的配置

  • 在类定义之前添加@Component注释,您需要在其中注入StudentJDBCTemplate实例

  • 在StudentJDBCTemplate的属性定义之前添加@Autowired注释

  • 例如

    @Component
    public class MyClass {
    
        @Autowired
        private StudentJDBCTemplate studentJDBCTemplate;
    
        // here you can implement a method and use studentJDBCTemplate it's already injected by spring.
    }
    
    我希望这会有帮助。

    可能会重复