Java 定义ApplicationContext.xml后,如何访问bean
我使用ApplicationContext访问我的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 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
public class MyClass {
@Autowired
private StudentJDBCTemplate studentJDBCTemplate;
// here you can implement a method and use studentJDBCTemplate it's already injected by spring.
}
我希望这会有帮助。可能会重复