Spring Constructor Injection Weird Error - spring

I have encountered below BeanDefinitionDecorator error at below constructor-arg dependency line in Bean XML (root-context.xml) in Eclipse, but no issue when using setter injection with property element, appreciate if anyone here could provide advice, as not able to identify the root cause even after search through Internet. Thanks in advance.
Error encountered
"Multiple annotations found at this line:
Cannot locate BeanDefinitionDecorator for element [constructor-arg]
cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'constructor-arg'.
Configuration problem: Cannot locate BeanDefinitionDecorator for element [constructor-arg] Offending resource: file [C:/Users/Administrator/
workspace/EsmProject/src/main/webapp/WEB-INF/spring/root-context.xml]"
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<beans:bean id="myObject" class="com.packapp.MyObject"></beans:bean>
<beans:bean id="homeDAO" class="com.packapp.HomeDAOImpl">
<constructor-arg><ref bean="myObject"/></constructor-arg>
</beans:bean>
<beans:bean id = "homeService" class="com.packapp.HomeServiceImpl">
<beans:property name="homeDAO" ref="homeDAO"></beans:property>
</beans:bean>
<context:component-scan base-package="com.packapp" />
</beans:beans>
public class MyObject {
private String homeName;
private String homeAddress;
public String getHomeName(){
return homeName;
}
public void setHomeName(String homeName){
this.homeName = homeName;
}
public String getHomeAddress(){
return homeAddress;
}
public void setHomeAddress(String homeAddress){
this.homeAddress = homeAddress;
}
}
#Repository
public class HomeDAOImpl implements HomeDAO {
private MyObject obj;
public HomeDAOImpl(MyObject obj){
this.obj = obj;
}
public String getAddress() {
return this.obj.getHomeAddress();
}
}
#Service
public class HomeServiceImpl implements HomeService {
private HomeDAO homeDAO;
public void setHomeDAO(HomeDAO homeDAO){
this.homeDAO = homeDAO;
}
public String getAddress() {
return this.homeDAO.getAddress();
}
}
#Controller
#RequestMapping("ctrl2")
public class HomeController2 {
private HomeService homeService;
#Autowired(required=true)
#Qualifier(value="homeService")
public void setHomeService (HomeService hs){
this.homeService = hs;
}
#RequestMapping(value = "/site2", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate + this.homeService.getAddress());
return "home2";
}
}

I think <constructor-arg><ref bean="myObject"/></constructor-arg>
must be <beans:constructor-arg><beans:ref bean="myObject"/></beans:constructor-arg>
because you have a prefix for elements in spring-beans.xsd.

Related

#Autowired Not Working with XML Configuration Spring

I have a simple beans.xml file as below.
It has two beans :
Employee and
Address
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="address" class="com.atul.test.Address"></bean>
<bean id="employee" class="com.atul.test.Employee">
</bean>
</beans>
I have below Java Classes and Configuration.
public class Employee {
#Autowired
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public void checkAddress(){
System.out.println("Your address is = "+this.address);
this.address.vomit();
}
}
public class Address {
public void vomit(){
System.out.println("Vomit !!!!");
}
}
public class App
{
public static void main( String[] args )
{
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
Employee employee = (Employee)ctx.getBean("employee");
System.out.println("Employee = "+employee);
Address address = (Address)ctx.getBean("address");
System.out.println("address = "+address);
System.out.println("employee.address = "+employee.getAddress());
}
}
The issue :
Even though , I have #Autowired on Employee class , Address is not getting injected
I am getting employee.address as NULL
ctx.getBean("employee") and ctx.getBean("address") both are returning correct beans (non null)
As per my understanding , #Autowired should work as long as both beans are available in Spring context , which is true in this case
You need <context:annotation-config/> in you spring XML to enable Spring annotation.
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:context = "http://www.springframework.org/schema/context"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean id="address" class="com.atul.test.Address"></bean>
<bean id="employee" class="com.atul.test.Employee"></bean>
</beans>
You must use #Component on your class Address
#Component
public class Address {
public void vomit(){
System.out.println("Vomit !!!!");
}
}
You must use #Component on all class that you want to use with autowired

Autowire on new-ing up an object

I've a scenario where a bean I'm using has some fields populated from properties file while others need to be populated dynamically (from a api call).
Here is my bean:
#Configuration
#ConfigurationProperties(prefix="studio")
public class Studio {
private String areaCode; // loads from application.properties
private String hours; // loads from application.properties
private String groupCode; // loads from application.properties
private Address address; // loads from a api
private String id; // loads from a api
public Studio(String id, String city, String subdivision,
String addressLine1, String postalCode) {
Address address = Address.builder()
.street(addressLine1)
.city(city)
.postalCode(postalCode)
.state(subdivision)
.build();
this.id = id;
this.address = address;
}
}
Now the method that populates the dynamic fields is like this:
private List<Studio> getStudioDataFromApi(ResponseEntity<String> exchange)
throws Exception {
List<Studio> infoList = $(exchange.getBody())
.xpath("Area[TypeCode=\"CA\"]")
.map(
Area -> new Studio(
$(Area).child("Id").text(String.class),
$(Area).child("Address").child("City").text(String.class),
$(Area).child("Address").child("Subdivision").text(String.class),
$(Area).child("Address").child("AddressLine1").text(String.class),
$(Area).child("Address").child("PostalCode").text(String.class))
);
return infoList;
}
I Autowire Studio in that class. Now whenever I run this, I get the fields that are populated from the properties file as null. I can see the reason, which is, new doesn't know anything about the autowired bean. My question is how can I use both? i.e. use a bean that has always some fields populated from a config when its new-ed up.
Context xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean class="org.springframework.batch.core.scope.StepScope" />
<bean id="ItemReader" class="com.sdm.studio.reader.StudioReader" scope="step">
<property name="studio" ref="Studio" />
</bean>
<bean id="Studio" class="com.sdm.studio.domain.Studio" />
</bean>
[edit: full code example shown here is also on github ]
Try this:
//This class contains read-only properties, loaded from Spring Externalized Configuration
#Component
#ConfigurationProperties(prefix="studio")
public class Studio {
private String areacode; // loads from application.properties
//... also add other read-only properties and getters/setters...
public String getAreacode() {
return areacode;
}
public Studio setAreacode(String areacode) {
this.areacode = areacode;
return this;
}
}
//Just a POJO
class FullStudio {
private String id;
private Address address;
FullStudio(String id, String city, String areaCode) {
this.id = id;
this.address = new Address(id, city, areaCode);
}
#Override
public String toString() {
return "FullStudio{" +
"id='" + id + '\'' +
", address=" + address +
'}';
}
}
class Address{
String id;
String city;
String areaCode;
public Address(String id, String city, String areaCode) {
this.id = id;
this.city = city;
this.areaCode = areaCode;
}
#Override
public String toString() {
return "Address{" +
"id='" + id + '\'' +
", city='" + city + '\'' +
", areaCode='" + areaCode + '\'' +
'}';
}
}
What we are doing here is allowing Spring to control the lifecycle of the Studio class. You don't need to create a new Studio yourself. Spring does that when it starts up. Since it is also a #ConfigurationProperties class it will also populate values from Spring Externalized Configuration Note: you also need public getters and setters so that Spring can populate the values for you.
FullStudio is not a Spring managed class. You create your own FullStudio with values from Studio and any other api.
And here is a class that is not configured with Java Config #Configuration but instead is managed by an xml configuration:
public class StudioReader {
private Studio wiredstudio;
public String getMessage(){
return wiredstudio.getAreacode();
}
public StudioReader setWiredstudio(Studio studio) {
this.wiredstudio = studio;
return this;
}
}
And we use this mycontext.xml file to create this bean with the reference to wiredstudio. The Studio that Spring wires in here comes from our Studio instance configured with JavaConfig. The ref attribute of studio is the name that Spring automatically chose for us based on the name of the Studio class when it instantiated it into our spring application context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="studioReaderReader" class="com.example.StudioReader" >
<property name="wiredstudio" ref="studio" />
</bean>
</beans>
Personally, I think it is more trouble than its worth for new projects to combine xml and Java Configuration for Spring beans, but it can be done.
Here is a test class that shows how our Studio class can be used from classes created with Spring Java Config and XML config:
#RunWith(SpringRunner.class)
#SpringBootTest
public class StartAppTest {
#Autowired private Studio studio;
#Autowired private StudioReader studioReader;
#Test
public void contextok() throws Exception {
}
#Test
public void fullStudio() throws Exception {
FullStudio fs = new FullStudio("1", "Denver", studio.getAreacode());
System.out.println("stdio is: " + fs);
assertEquals("303", studio.getAreacode());
}
#Test
public void loadstudioreader() throws Exception {
assertEquals("303",studioReader.getMessage());
}
}
In order to run this test, you will need 2 more files:
#SpringBootApplication
#ImportResource("classpath:mycontext.xml")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
and our application.properties file:
studio.areacode=303

#XmlPath not working

#XmlPath is not working.
Customer.java
import org.eclipse.persistence.oxm.annotations.XmlPath;
#XmlRootElement(name= "Customer")
public class Customer {
private String CustomerId;
private String organizationCode;
private Extn extn;
private String organizationName;
private int reset;
private CustomerSchedulingPreferences customerSchedulingPreferences;
private ArrayList<RestrictedState> restrictedStateList;
#XmlAttribute
public String getCustomerId() {
return CustomerId;
}
public void setCustomerId(String customerId) {
CustomerId = customerId;
}
#XmlAttribute
public String getOrganizationCode() {
return organizationCode;
}
public void setOrganizationCode(String organizationCode) {
this.organizationCode = organizationCode;
}
#XmlElement(name="Extn")
public Extn getExtn() {
return extn;
}
public void setExtn(Extn extn) {
this.extn = extn;
}
#XmlPath("BuyerOrganization/#OrganizationName")
public String getOrganizationName() {
return organizationName;
}
public void setOrganizationName(String organizationName) {
this.organizationName = organizationName;
}
#XmlPath("BuyerOrganization/Extn/USSCORestrictedStateList")
#XmlElement(name = "USSCORestrictedState")
public ArrayList<RestrictedState> getRestrictedStateList() {
return restrictedStateList;
}
public void setRestrictedStateList(ArrayList<RestrictedState> restrictedStateList) {
this.restrictedStateList = restrictedStateList;
}
#XmlPath("BuyerOrganization/Extn/USSCORestrictedStateList/#Reset")
public int getReset() {
return reset;
}
public void setReset(int reset) {
this.reset = reset;
}
#XmlElement(name="CustomerSchedulingPreferences")
public CustomerSchedulingPreferences getCustomerSchedulingPreferences() {
return customerSchedulingPreferences;
}
public void setCustomerSchedulingPreferences(
CustomerSchedulingPreferences customerSchedulingPreferences) {
this.customerSchedulingPreferences = customerSchedulingPreferences;
}
}
Client.java
import javax.xml.transform.stream.StreamResult;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
public class Client
{
public static void main(String[] args)throws IOException
{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Marshaller marshaller = (Marshaller)context.getBean("jaxbMarshallerBean");
Customer customer=new Customer();
customer.setCustomerId("12345");
customer.setOrganizationCode("SUPPLY");
Extn extn = new Extn();
extn.setExtnBillCreditCode("000");
extn.setExtnBillSubscriptionId("132131");
customer.setExtn(extn);
RestrictedState resState1= new RestrictedState();
resState1.setOrgCode("952121");
resState1.setRestrictedStateCode("IN");
RestrictedState resState2= new RestrictedState();
resState2.setOrgCode("60325");
resState2.setRestrictedStateCode("IL");
ArrayList<RestrictedState> restrictedStateList = new ArrayList<RestrictedState>();
restrictedStateList.add(resState1);
restrictedStateList.add(resState2);
CustomerSchedulingPreferences custSchedPref = new CustomerSchedulingPreferences();
custSchedPref.setIsLineShipComplete("Y");
custSchedPref.setIsLineShipSingleNode("N");
custSchedPref.setOptimizationType("03");
customer.setCustomerSchedulingPreferences(custSchedPref);
customer.setRestrictedStateList(restrictedStateList);
marshaller.marshal(customer, new StreamResult(new FileWriter("customer.xml")));
System.out.println("XML Created Sucessfully");
}
}
applicationContext.Xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">
<oxm:jaxb2-marshaller id="jaxbMarshallerBean">
<oxm:class-to-be-bound name="com.javatpoint.Customer"/>
</oxm:jaxb2-marshaller>
</beans>
Structure of Output needed :
<Customer CustomerID="952121" OrganizationCode="SUPPLY" >
<Extn ExtnBillCreditCode="000" ExtnBillSubscriptionID="952121" />
<BuyerOrganization OrganizationName="Buy.com1" >
<Extn>
<USSCORestrictedStateList Reset="Y">
<USSCORestrictedState OrganizationCode="952121" RestrictedStateCode="IN"/>
</USSCORestrictedStateList>
</Extn>
</BuyerOrganization>
<CustomerSchedulingPreferences IsLineShipComplete="" IsLineShipSingleNode="" />
</Customer>
================================================================================
Please help me in resolving this:
Currently i am getting output like below :
<Customer organizationCode="SUPPLY" customerId="12345">
<CustomerSchedulingPreferences IsLineShipSingleNode="N" IsLineShipComplete="Y"/>
<Extn ExtnBillSubscriptionID="132131" ExtnBillCreditCode="000"/>
<reset>0</reset>
<USSCORestrictedState restrictedStateCode="IN" OrganizationCode="952121"/>
<USSCORestrictedState restrictedStateCode="IL" OrganizationCode="60325"/>
</Customer>
To leverage the #XmlPath extension you need to be using EclipseLink MOXy as your JAXB provider.
eclipselink.jar on your classpath
a jaxb.properties file in the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Below is a link that will help set this up:
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/Spring

wiring properties with spring's p namespace doesn't work

I'm trying wiring properties with spring's p namespace. The problem is I got "org.springframework.beans.factory.BeanDefinitionStoreException: (...) cvc-complex-type.3.2.2: Attribute 'p:instrument-ref' is not allowed to appear in element 'bean'."
Please look at my xml, classes and tell me what I'm doing wrong.
performers.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="guitar" class="com.competition.Guitar"></bean>
<bean id="instrumentalist" class="com.competition.Instrumentalist"
p:instrument-ref="guitar" p:song="some song">
</bean>
</beans>
Instrumentalist.java:
package com.competition;
public class Instrumentalist implements Performer {
private Instrument instrument;
private String song;
public Instrument getInstrument() {
return instrument;
}
public void setInstrument(Instrument instrument) {
this.instrument = instrument;
}
public String getSong() {
return song;
}
public void setSong(String song) {
this.song = song;
}
public void perform() {
System.out.println("Playing " + song);
instrument.play();
}
}
Guitar.java:
package com.competition;
public class Guitar implements Instrument {
public void play() {
System.out.println("play on guitar");
}
}

Creating a list of instantiated beans in Spring

I have a bean Employee as:
public class Employee {
private int empId;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
}
An EmployeeList class which has looks like:
public class EmployeeList {
#Autowired
public Employee[] empList;
}
The spring config file:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="empBean" class="Employee" scope="prototype">
</bean>
<bean id="empBeanList" class="EmployeeList">
</bean>
</beans>
The main method class:
public class App
{
public static void main( String[] args )
{
ApplicationContext empContext = new ClassPathXmlApplicationContext(
"employee-module.xml");
EmployeeList objList = (EmployeeList) empContext.getBean("empBeanList");
Employee obj = (Employee) empContext.getBean("empBean");
obj.setEmpId(1);
System.out.println(obj.getEmpId());
System.out.println("length " + objList.empList.length);
Employee obj1 = (Employee) empContext.getBean("empBean");
obj1.setEmpId(2);
System.out.println(obj1.getEmpId());
System.out.println("length " + objList.empList.length);
Employee obj2 = (Employee) empContext.getBean("empBean");
System.out.println("length " + objList.empList.length);
}
}
The count of Employee instances I get is always 1. Why it is not incremented when I get the bean instance multiple times. The Employee bean has scope as prototype.
Because getting a new prototype instance doesn't magically add it to a previously instantiated bean array.
When the context starts up, a single employee bean is instantiated and injected in the empBeanList bean, and then the empList bean is created and doesn't change anymore.

Resources