简体   繁体   中英

How to access beans from the applicationContext.xml in my service layer.

How to access beans from the applicationContext.xml in my service layer.

I am working on a Spring Web MVC project and that issue is that my service layer needs a URL, User ID and Password to do a web post to a server to save my data. I dont want to hardcode the URL, User ID and password in the Java Code of the Service Layer so I would like to put them into the applicationContent.xml file but I dont know how to access them from the service layer.

Can someone please help me out with this.. example code would be great.

If your service is already a Spring managed bean, it should be trivial:

Add 3 properties to your service class ( url , userId and password ) along with their corresponding setters. Then you can set the values via your context:

<bean id="yourService" class="xxx.yyy.zz.YourService">
  <property name="url" value="http://someurl.com"/>
  <property name="userId" value="username"/>
  <property name="password" value="passwd"/>
</bean>

Had a similar question. May be this link will be of help. Spring MVC 3.0 - Service layer using annonations

Create a map of the values in dispatcher-servlet.xml and access it programmatically in your class. Or better inject the values to your bean in the xml file itself. If you would rather have these values as environmental variables, that is also possible in Spring. Use a "propertyplaceholderconfigurer" for reading the external variables. Let me know if you need further help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM