No constructor with 3 arguments defined in class? - java

Let me clear it, I'm a completely beginner in Spring framework.
I've three class files, Now i'm getting an error into beans.xml. You could take a look into my codes.
Here is MyAddress.java:
package com.project;
public class MyAddress {
private String city;
private String state;
private String address;
public void Address(String city, String state, String address){
this.city=city;
this.state=state;
this.address=address;
}
public String toString(){
return city+" "+state+" "+address;
}
}
Here is my Employee.java
package com.project;
public class Employee {
private int id;
private String name;
private MyAddress address;
public Employee(){
System.out.print("Default constructor..");
}
public void Employee(int id, String name, MyAddress address){
this.id=id;
this.name=name;
this.address=address;
}
public void show(){
System.out.println(id+" "+name);
System.out.println(address.toString());
}
}
Here is my MainProgram.java
package com.project;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainProgram {
public static void main(String[] args){
ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
Employee em=(Employee)ac.getBean("e");
em.show();
}
}
and finally here is my beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="e" class="com.project.MyAddress">
<constructor-arg value="USA" type="String"></constructor-arg>
<constructor-arg value="Delhi" type="String"></constructor-arg>
<constructor-arg value="Bangalore" type="String"></constructor-arg>
</bean>
<bean id="e2" class="com.project.Employee">
<constructor-arg value="123" type="int"></constructor-arg>
<constructor-arg value="raj"></constructor-arg>
<constructor-arg>
<ref bean="e"/>
</constructor-arg>
</bean>
</beans>
I'm getting an error in beans.xml files as No constructor with 3 arguments defined in class
PLease help, what's that mean?
Surely, help would be appreciated!!

This
public void Address(String city, String state, String address)
should be
public MyAddress(String city, String state, String address)
You got the class name wrong in your constructor, and in addition, constructors don't have a return type.
You have a similar error for Employee :
public void Employee(int id, String name, MyAddress address)
should be
public Employee(int id, String name, MyAddress address)

As defined here,
"A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type"

In the MyAddress class instead of creating a constructor you created a Address method,
changing public void Address(...) to public MyAddress(...) will make it work

The address class has a default constructor. Omit void keyword from method.

Related

Invalid property 'name' of bean class [Country]: Bean property 'name' is not writable or has an invalid setter method. Did you mean 'cname'?

I am new to springs, so I was just trying to implement inheritance in spring.
Customer.java
public class Customer {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Country.java
public class Country {
String cname;
String city;
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Main.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String args[]){
ApplicationContext context = new ClassPathXmlApplicationContext("Bean1.xml");
Customer cus = (Customer) context.getBean("customer");
System.out.println(cus.getName());
Country con = (Country) context.getBean("country");
System.out.println(con.getCname());
}
}
Bean1.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"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "customer" class = "Customer">
<property name = "name" value = "Garima"/>
</bean>
<bean id ="country" class="Country" parent="customer">
<property name = "cname" value = "India"/>
<property name = "city" value = "Delhi"/>
</bean>
</beans>
Every time I run this without parent in Bean1.xml, this is running fine. As soon as I add parent , I receive the below mentioned error.
Error : Invalid property name of bean class [Country]: Bean property name is not writable or has an invalid setter method. Did you mean cname?
I have noticed this case with many other examples as well.
Can someone please help me with this?
This is because your bean definition suggests that Customer is parent of Country but your class Country doesn't extend Customer
<bean id ="country" class="Country" parent="customer">
So you have two options
Either remove parent="customer" from your bean definition
OR Extend Customer in Country class like
public class Country extends Customer{...

How can I get the name and id from my java bean?

I am trying to run a test function to get the name and id of my bean from the config file. I have tried everything I can think of up until now and no luck. I get about 40 lines of errors that I have no idea how to read. I am certain it is something simple but I am just not connecting the dots. How can I fix this?
package com.intraedge.spring.springcore;
class Employee {
private int id;
private String name;
// public int getId(int args) {
// id = args;
// return id;
// }
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
package com.intraedge.spring.springcore;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("config.xml");
Employee emp = (Employee)ctx.getBean("emp");
System.out.println("Name: "+emp.getName(name.value));
// System.out.println("Id: "+emp.getId(3));
}
}
<?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"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean name="emp" class="com.intraedge.spring.springcore.Employee">
<property name="id">
<value>20</value>
</property>
<property name="name">
<value>Casandra</value>
</property>
</bean>
</beans>
After updating the namespaces like suggested, there was a new error relating to the getter/setter of the bean ID. I fixed it by adding in the proper getter/setter functions and removing any arguments from the function calls.
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}

Address value shows null

I have two classes Student and Address which implements IStudent ans IAddress interfaces respectively. Student class has a relationship with Address class. That is why i have declared a reference member of it.
public class Student implements IStudent {
private String code;
private String name;
#Autowired
private IAddress address;
#Override
public String getCode() {
return this.code;
}
#Override
public String getName() {
return this.name;
}
public void setCode(String code) {
this.code = code;
}
public void setName(String name) {
this.name = name;
}
public IAddress getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
}
and I have Address class
public class Address implements IAddress{
private String city;
private String pinCode;
private String houseNo;
private String roadName;
#Override
public String getCity() {
return this.city;
}
#Override
public String getPinCode() {
return this.pinCode;
}
#Override
public String getHouseNo() {
return this.houseNo;
}
#Override
public String getRoadName() {
return this.roadName;
}
public void setCity(String city) {
this.city = city;
}
public void setPinCode(String pinCode) {
this.pinCode = pinCode;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public void setRoadName(String roadName) {
this.roadName = roadName;
}
}
In my applicationContext.xml file i have written the following bean definitions
<?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-4.0.xsd">
<bean id="studentbean" class="main.Student">
<property name="code" value="S001"></property>
<property name="name" value="Subhabrata Mondal"></property>
</bean>
<bean id="addressbean" class="main.Address">
<property name="houseNo" value="119/2"></property>
<property name="roadName" value="South Avenue"></property>
<property name="city" value="Delhi"></property>
<property name="pinCode" value="110005"></property>
</bean>
</beans>
When i have checked Student object after initialization of bean, name and code has assigned with setter method. But the address is not assigned. Thus it shows null value for address. I have marked address with #Autowired annotation. Can you please help?
ApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) factory.getBean("studentbean");
System.out.println(student.getAddress());
you need to explicitly wire to Address not IAddress since the CI only knows Address, if you want to wired
#Autowired
private Address address;
or you need to define a bean with type IAddress but make sure you do not have more than implementation or spring will get confused, if you have more than one implementation use can qualifiers to clear the ambiguity
This whole example is kind of strange but you can get rid of the #Autowired annotation and use following bean configuration instead;
<bean id="studentbean" class="main.Student">
<property name="code" value="S001"></property>
<property name="name" value="Subhabrata Mondal"></property>
<property name="address" >
<ref local="addressbean"/>
</property>
</bean>

spring - read property value from properties file in static field of class

I have one utility class where i have one method which requires username and password to connect other url. I need to kept that username in properties file so that i can change it any time. But as i am using it in static method (being utility class) , Issue is it is showing null .(i.e. it is not able to read from properties file).
But when i ckecked that values in some other controller they are getting there.
So my question is how to read property value in static field
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:/myservice_detaults.properties</value>
<value>classpath*:/log4j.properties</value>
</list>
</property>
</bean>
//in Utitlity class code
#Value("${app.username}")
static String userName;
public static connectToUrl(){
//use userName
//userName showing null
}
In you Utility class you can have a setter method to set the properties and then you can use MethdInvokingFactoryBean.
class Utility{
static String username;
static String password;
public static setUserNameAndPassword(String username, String password){
Utility.username = username;
Utility.password = password;
}
//other stuff
}
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:/myservice_detaults.properties</value>
<value>classpath*:/log4j.properties</value>
</list>
</property>
</bean>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="foo.bar.Utility.setUserNameAndPassword"/>
<property name="arguments">
<list>
<value>${username}</value>
<value>${password}</value>
</list>
</property>
</bean>
Or using the #Value over the non-static setter method for username
eg.
#Value("${app.username}")
public void setUserName(String userName) {
UtilityClass.userName = userName;
}
Read property value from properties file in static field of class using Java based spring configuration.
Example :
// The property file to store fields.
user.properties
username=Elijah Wood
age=26
language=English
// This class holds the static values
package org.javahive.propertyreader.example;
public class UserDetails {
static String username;
static String age;
static String language;
public static void setUserValues(String username, String age, String language) {
UserDetails.username = username;
UserDetails.age = age;
UserDetails.language = language;
}
}
//Spring configuration class
package org.javahive.propertyreader.example;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
#Configuration
#ComponentScan(value = { "org.javahive.propertyreader.example" })
#PropertySource("classpath:user.properties")
public class PropertyReaderConfig {
#Value("${user}")
private String username;
#Value("${age}")
private String age;
#Value("${language}")
private String language;
#Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public MethodInvokingFactoryBean methodInvokingFactoryBean() {
MethodInvokingFactoryBean mifb = new MethodInvokingFactoryBean();
mifb.setStaticMethod("org.javahive.propertyreader.example.UserDetails.setUserValues");
mifb.setArguments(new String[] { this.username, this.age, this.language });
return mifb;
}
/**
* #return the name
*/
public String getName() {
return username;
}
/**
* #param name
* the name to set
*/
public void setName(String name) {
this.username = name;
}
/**
* #return the age
*/
public String getAge() {
return age;
}
/**
* #param age
* the age to set
*/
public void setAge(String age) {
this.age = age;
}
/**
* #return the language
*/
public String getLanguage() {
return language;
}
/**
* #param language
* the language to set
*/
public void setLanguage(String language) {
this.language = language;
}
}
//The main class.
package org.javahive.propertyreader.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(PropertyReaderConfig.class);
System.out.println("User Name : " + UserDetails.username);
System.out.println("Age : " + UserDetails.age);
System.out.println("Language : " + UserDetails.language);
}
}
Try this :
Make your class a Component
#Component
public class UserXXXUtils {
private static Integer trustXXXMask;
#Value("${trustXXXMask}")
public void setTrustXXXMask(Integer trustXXXMask) {
UserXXXUtils.trustXXXMask = trustXXXMask;
}
//Access anywhere in the class
}
Spring doesn't allow to inject values into non-final static fields but make your field private and it should works.
Or just
<bean id="constants" class="com.foo.constants.CommonConstants">
<property name="username" value="${username}"/>
</bean>

Adding properties for a bean

I have following bean class. I want to define this bean into the xml file.
I want to know which objects of this bean are added as a property of the bean in the xml?
public class Mybean{
public String name;
public String address;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
public String getAddress()
{
return address;
}
}
Since you have getters and setters for the name and address fields they can both serve as properties.
<bean id="mybean" class="package.to.MyBean">
<property name="name" value="something"/>
<property name="address" value="something"/>
</bean>
Reference: http://www.springbyexample.org/examples/intro-to-ioc-basic-setter-injection.html
Let your class implement InitializingBean, then in the afterPropertiesSet() method, you can check which property has been set by spring

Categories