learner420
learner420

Reputation: 182

How to access the bean, Once I define the ApplicationContext.xml

I was using the ApplicationContext as follows to access my beans:

ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");
 StudentJDBCTemplate studentJDBCTemplate = 
      (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");

now I want to Create an applicationContext.xml and there I am using component-scan as follows:

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

so that I don't have to create ApplicationContext object to access the bean, and put it under my WEB-INF folder as explained here

My question is, How do I access my beans now? Since there is no ApplicationContext Object at my disposal now.

Upvotes: 0

Views: 607

Answers (1)

Selim Ok
Selim Ok

Reputation: 1161

You can use @Autowired annotation. For that

  1. Add <context:annotation-config/> into your applicationContext.xml so that annotation driven configuration is enabeled.

  2. Add @Component annotation right before the class definition, where you need to inject your StudentJDBCTemplate instance.

  3. Add @Autowired annotation right before of the attribute definiton of StudentJDBCTemplate.

for examle

@Component
public class MyClass {

    @Autowired
    private StudentJDBCTemplate studentJDBCTemplate;

    // here you can implement a method and use studentJDBCTemplate it's already injected by spring.
}

I hope it helps.

Upvotes: 1

Related Questions