i m new to spring. i want to retrieve some field of user details from ldap and display on the jsp page. how can i retrieve this filed from ldap on page load?
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="contextSource"
class="org.springframework.ldap.core.support.LdapContextSource">
<property name="url" value="ldap://url:389" />
<property name="base" value="dc" />
<property name="userName" value="uid=admin,ou=system" />
<property name="password" value="secret" />
</bean>
<bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
<constructor-arg ref="contextSource" />
</bean>
<bean id="ldapContact"
class="org.LDAPContactDAO">
<property name="ldapTemplate" ref="ldapTemplate" />
</bean>
</beans>
It give me following exception
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ldapContact' defined in class path resource [springldap.xml]: Cannot resolve reference to bean 'ldapTemplate' while setting bean property 'ldapTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ldapTemplate' defined in class path resource [springldap.xml]: Cannot resolve reference to bean 'contextSource' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contextSource' defined in class path resource [springldap.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'userName' of bean class [org.springframework.ldap.core.support.LdapContextSource]: Bean property 'userName' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1325)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.SpringFrameworkLDAPClient.main(SpringFrameworkLDAPClient.java:20)
I have write down some class file
package org;
public class ContactDTO {
private String displayName;
// lastName = Person.sn
private String firstName;
private String company;
private String department;
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String toString() {
StringBuffer contactDTOStr = new StringBuffer("Person=[");
contactDTOStr.append(" firstName = " + firstName);
contactDTOStr.append(" ]");
return contactDTOStr.toString();
}
}
//interface ContactDAO
package org;
import java.util.List;
public interface ContactDAO {
public List getAllContactNames();
/*public List getContactDetails(String commonName);*/
}
// LDAPContactDAO
package org;
import java.util.List;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
public class LDAPContactDAO implements ContactDAO{
#Override
public List getAllContactNames() {
// TODO Auto-generated method stub
return null;
}
/*public List getContactDetails(String objectclass){
AndFilter andFilter = new AndFilter();
andFilter.and(new EqualsFilter("objectClass",objectclass));
System.out.println("LDAP Query " + andFilter.encode());
return ldapTemplate.search("", andFilter.encode(),new ContactAttributeMapper());
}*/
}
package org;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.dao.DataAccessException;
public class SpringFrameworkLDAPClient {
public static void main(String[] args) {
//Resource resource = new ClassPathResource("/SpringLDAPClient/src/com/javaworld/sample/springldap.xml");
//System.out.println(resource.toString());
try {
Resource resource = new ClassPathResource("springldap.xml");
BeanFactory factory = new XmlBeanFactory(resource);
System.out.println(factory.toString() + "\n");
ContactDAO ldapContact = (LDAPContactDAO)factory.getBean("ldapContact");
/*List contactList = ldapContact.getContactDetails("30662");*/
//List contactList =ldapContact.getAllContactNames();
//System.out.println(contactList.size());
/*int count = 0;
for( int i = 0 ; i < contactList.size(); i++){
System.out.print("Email: " + ((ContactDTO) contactList.get(i)).getMail() + " ");
System.out.println("SAP: " + ((ContactDTO) contactList.get(i)).getSap());
count++;
}
System.out.println("\n" + count);
*/
} catch (DataAccessException e) {
System.out.println("Error occured " + e.getCause());
}
}
}
But i am not able display this user details on jsp page? please any body know about this reply
The important part of the error message is:
Error creating bean with name 'contextSource'
defined in class path resource [springldap.xml]:
Error setting property values;
nested exception is org.springframework.beans.NotWritablePropertyException:
Invalid property 'userName'
of bean class [org.springframework.ldap.core.support.LdapContextSource]:
Bean property 'userName' is not writable or has an invalid setter method.
Does the parameter type of the setter match the return type of the getter?
I don't know wich version of Spring LDAP You're using, but userName seems to be deprecated in version 1.2 and completely removed in version 1.3 - try userDn instead, and see reference section on DirContext Authentication
And on how to get user details from LDAP try the reference: User Authentication using Spring LDAP
Or even better: use Spring Security with LDAP Authentication.
Related
This is my Spring main class
public class AppConfigSpring {
private static Log logger = LogFactory.getLog(AppConfigSpring.class);
public static void main(String[] args) {
logger.info("Log info message");
logger.debug("Debug log");
AbstractApplicationContext appContext = new ClassPathXmlApplicationContext("spring.xml");
appContext.registerShutdownHook();
Person beanSecurityPersonal = (Person) appContext.getBean("securityPersonal");
beanSecurityPersonal.printingName();
beanSecurityPersonal.officeAddress();
}}
Below is my spring bean class
public class SecurityPersonal implements Person {
private String firstName;
private String lastName;
#Autowired
#Qualifier("securityPersonal")
private Address officeAddressSecurity;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Address getOfficeAddressSecurity() {
return officeAddressSecurity;
}
public void setOfficeAddressSecurity(Address officeAddressSecurity) {
this.officeAddressSecurity = officeAddressSecurity;
}
#Override
public void printingName() {
StringBuilder secName = new StringBuilder();
secName.append("Security Personal Name : ").append(getFirstName()).append(" ").append(getLastName());
System.out.println(secName.toString());
}
#Override
public void officeAddress() {
StringBuilder secAddress = new StringBuilder();
secAddress.append("Office Address : ").append(" State - ").append(getOfficeAddressSecurity().getState())
.append(" City - ").append(getOfficeAddressSecurity().getCity()).append(" Pincode - ")
.append(getOfficeAddressSecurity().getPincode()).append("\n");
System.out.println(secAddress.toString());
}
#Override
public void shippingAddress() {
}
#Override
public void itemsListDetails() {
}}
And Below is my exception
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityPersonal': Unsatisfied dependency expressed through field 'officeAddressSecurity'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.sunil.javabrains.Address' available: expected single matching bean but found 2: officeAddress,shippingAddress
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityPersonal': Unsatisfied dependency expressed through field 'officeAddressSecurity'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.sunil.javabrains.Address' available: expected single matching bean but found 2: officeAddress,shippingAddress
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:144)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:85)
at org.sunil.javabrains.AppConfigSpring.main(AppConfigSpring.java:20)
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.sunil.javabrains.Address' available: expected single matching bean but found 2: officeAddress,shippingAddress
at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:220)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1265)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
... 15 more
Spring xml Config
<beans default-init-method="initMethod"
default-destroy-method="destroyMethod">
<bean id="officeAddress" class="org.sunil.javabrains.Address">
<qualifier type="org.springframework.beans.factory.annotation.Qualifier" value="securityPersonal"></qualifier>
<property name="state" value="Maharashtra"></property>
<property name="city" value="Mumbai"></property>
<property name="pincode" value="400083"></property>
</bean>
<bean id="shippingAddress" class="org.sunil.javabrains.Address">
<property name="state" value="Maharashtra"></property>
<property name="city" value="Pune"></property>
<property name="pincode" value="411045"></property>
</bean>
<bean id="securityPersonal" class="org.sunil.javabrains.SecurityPersonal">
</bean>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"></bean>
</beans>
Try to use following spring config (Spring - Annotation Based Configuration):
<context:annotation-config/>
And use the bean id as qualifier!
#Qualifier("officeAddress")
spring.xml
<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 id="officeAddress" class="org.sunil.javabrains.Address">
<property name="state" value="Maharashtra"></property>
<property name="city" value="Mumbai"></property>
<property name="pincode" value="400083"></property>
</bean>
<bean id="shippingAddress" class="org.sunil.javabrains.Address">
<property name="state" value="Maharashtra"></property>
<property name="city" value="Pune"></property>
<property name="pincode" value="411045"></property>
</bean>
<bean id="securityPersonal" class="org.sunil.javabrains.SecurityPersonal" />
</beans>
SecurityPersonal.java
public class SecurityPersonal implements Person {
private String firstName;
private String lastName;
#Autowired
#Qualifier("officeAddress")
private Address officeAddressSecurity;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Address getOfficeAddressSecurity() {
return officeAddressSecurity;
}
public void setOfficeAddressSecurity(Address officeAddressSecurity) {
this.officeAddressSecurity = officeAddressSecurity;
}
#Override
public void printingName() {
StringBuilder secName = new StringBuilder();
secName.append("Security Personal Name : ").append(getFirstName()).append(" ").append(getLastName());
System.out.println(secName.toString());
}
#Override
public void officeAddress() {
StringBuilder secAddress = new StringBuilder();
secAddress.append("Office Address : ").append(" State - ").append(getOfficeAddressSecurity().getState())
.append(" City - ").append(getOfficeAddressSecurity().getCity()).append(" Pincode - ")
.append(getOfficeAddressSecurity().getPincode()).append("\n");
System.out.println(secAddress.toString());
}
#Override
public void shippingAddress() {
}
#Override
public void itemsListDetails() {
}
}
output
Security Personal Name : null null
Office Address : State - Maharashtra City - Mumbai Pincode - 400083
EDIT
The problem is that your qualifier name is equal to the ID of the bean (id=securityPersonal class=org.sunil.javabrains.SecurityPersonal)! So you can't use this ID as qualifier. You can use another ID to define the address with the qualifier.
e.g.
SecurityPersonal.java
#Autowired
#Qualifier("addressForSecurityPersonal")
private Address officeAddressSecurity;
spring.xml
<bean id="officeAddress" class="org.sunil.javabrains.Address">
<qualifier type="org.springframework.beans.factory.annotation.Qualifier" value="addressForSecurityPersonal" />
<property name="state" value="Maharashtra"></property>
<property name="city" value="Mumbai"></property>
<property name="pincode" value="400083"></property>
</bean>
From the exception, it is clear that the below annotation used is incorrect
#Qualifier("securityPersonal")
private Address officeAddressSecurity;
Either use
#Qualifier("shippingAddress")
OR
#Qualifier("officeAddress")
instead.
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{...
I am new to Spring and I am try to make a application for learning but I am getting problem in Autowiring,I am adding my code. I am working on spring boot.
logincontroller:
package com.cloudnexus.spring.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.cloudnexus.spring.model.Login;
import com.cloudnexus.spring.model.User;
import com.cloudnexus.spring.service.UserService;
#Controller
public class LoginController {
#Autowired
UserService userService;
#RequestMapping(value = "/loginProcess", method = RequestMethod.POST)
public ModelAndView loginProcess(HttpServletRequest request, HttpServletResponse response,
#ModelAttribute("login") Login login) {
ModelAndView mav = null;
User user = userService.validateUser(login);
if (null != user) {
mav = new ModelAndView("welcome");
mav.addObject("firstname", user.getUsername());
} else {
mav = new ModelAndView("login");
mav.addObject("message", "Username or Password is wrong!!");
}
return mav;
}
}
////
Login POJO:
package com.cloudnexus.spring.model;
public class Login {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
User Pojo :
package com.cloudnexus.spring.model;
public class User {
private String username;
private String password;
private int IsActive;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getIsActive() {
return IsActive;
}
public void setIsActive(int isActive) {
IsActive = isActive;
}
}
UserDao :
package com.cloudnexus.spring.dao;
import com.cloudnexus.spring.model.Login;
import com.cloudnexus.spring.model.User;
public interface UserDao {
User validateUser(Login login);
}
UserDaoImpl
package com.cloudnexus.spring.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import com.cloudnexus.spring.model.Login;
import com.cloudnexus.spring.model.User;
public class UserDaoImpl implements UserDao{
#Autowired
DataSource datasource;
#Autowired
JdbcTemplate jdbcTemplate;
public User validateUser(Login login) {
String sql = "select * from users where username='" + login.getUsername() + "' and password='" + login.getPassword()
+ "'";
List<User> users = jdbcTemplate.query(sql, new UserMapper());
return users.size() > 0 ? users.get(0) : null;
}
}
class UserMapper implements RowMapper<User> {
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User user = new User();
user.setUsername(rs.getString("Name"));
user.setPassword(rs.getString("Password"));
user.setIsActive(rs.getInt("IsActive"));
return user;
}
}
UserService :
package com.cloudnexus.spring.service;
import com.cloudnexus.spring.model.Login;
import com.cloudnexus.spring.model.User;
public interface UserService {
User validateUser(Login login);
}
UserServiceImpl
package com.cloudnexus.spring.service;
import org.springframework.beans.factory.annotation.Autowired;
import com.cloudnexus.spring.dao.UserDao;
import com.cloudnexus.spring.model.Login;
import com.cloudnexus.spring.model.User;
public class UserServiceImpl implements UserService{
#Autowired
public UserDao userDao;
public User validateUser(Login login) {
return userDao.validateUser(login);
}
}
spring bean configuration file :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.cloudnexus.spring" />
<context:annotation-config />
<bean id="userService" class="com.cloudnexus.spring.service.UserServiceImpl">
<property name="userService" ref="userService"></property>
</bean>
<bean name="userDao" class="com.cloudnexus.spring.dao.UserDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="datasource" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value=";DatabaseName=" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
</beans>
#Autowired to LoginBean loginBean;
Created getter setter of LoginBean in Controller class and autowired setters;
Created constructor of Controller and autowired, as given in above code;
Below is the error which I am getting :
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginController': Unsatisfied dependency expressed through field 'userService': Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userDao': Error creating bean with name 'userDao' defined in ServletContext resource [/WEB-INF/springBeanConfiguration.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSource' of bean class [com.cloudnexus.spring.dao.UserDaoImpl]: Bean property 'dataSource' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDao' defined in ServletContext resource [/WEB-INF/springBeanConfiguration.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSource' of bean class [com.cloudnexus.spring.dao.UserDaoImpl]: Bean property 'dataSource' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userDao': Error creating bean with name 'userDao' defined in ServletContext resource [/WEB-INF/springBeanConfiguration.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSource' of bean class [com.cloudnexus.spring.dao.UserDaoImpl]: Bean property 'dataSource' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDao' defined in ServletContext resource [/WEB-INF/springBeanConfiguration.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSource' of bean class [com.cloudnexus.spring.dao.UserDaoImpl]: Bean property 'dataSource' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
java.lang.Thread.run(Thread.java:748)
Your jdbcTemplate bean expects a bean named datasource, like you have set-it-up here (in the ref=... part:
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="datasource" />
</bean>
But your datasource bean does not exist. The reason is because you have defined it as dataSource (notice the capital "S") in bean id="dataSource"
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value=";DatabaseName=" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
So change this to "datasource" e.g. bean id="datasource" or change the reference in your jdbcTemplate to ref="dataSource"
Also the <property name="url" value=";DatabaseName=" /> doesn't look correct, I think you miss the correct value here, ";DatabaseName=" looks wrong or incomplete.
UPDATE
Since you are using xml spring configuration, the #Autowired annotation in your UserDaoImpl and UserServiceImpl classes is unnecessary. However, the xml configuration requires that the equivalent getters/setters exist. So change your code as:
In your UserDaoImpl you do not need the dataSource bean at all, so we are removing it.
public class UserDaoImpl implements UserDao{
JdbcTemplate jdbcTemplate;
public User validateUser(Login login) {
String sql = "select * from users where username='" + login.getUsername() + "' and password='" + login.getPassword()
+ "'";
List<User> users = jdbcTemplate.query(sql, new UserMapper());
return users.size() > 0 ? users.get(0) : null;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
You do need however the jdbcTemplate bean and in your xml definition you are not setting it, so update also your spring xml file to :
<bean name="userDao" class="com.cloudnexus.spring.dao.UserDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
and
public class UserServiceImpl implements UserService{
private UserDao userDao;
public User validateUser(Login login) {
return userDao.validateUser(login);
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
Also you have another mistake in the spring xml configuration file. In the userService bean definition your are setting it again as a property:
<property name="userService" ref="userService"></property>
This is wrong, you should set the userDao there. Update it as:
<bean id="userService" class="com.cloudnexus.spring.service.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
In autowiring byType if the property type is matched with more than one bean then it would throw an exception, but I can't see any exception when I am using the annotation #Autowired and defined two beans with same property type.
Below is the code:
Employee.java:
public class Employee {
private int id;
private String name;
private int salary;
// Getter and Setter
}
Dept:
public class Dept {
#Autowired
private Employee emp;
public Employee getEmp() {
return emp;
}
public void setEmp(Employee emp) {
this.emp = emp;
}
#Override
public String toString() {
return emp.getName();
}
}
Beans.xml:
<bean id = "dept" class = "Dept"></bean>
<bean id = "emp" class = "Employee">
<property name="id" value="25"></property>
<property name="name" value="Ram"></property>
<property name="salary" value="32000"></property>
</bean>
<bean id = "emp1" class = "Employee">
<property name="id" value="25"></property>
<property name="name" value="Sanju"></property>
<property name="salary" value="32000"></property>
</bean>
AppMain.java:
public class AppMain {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
Dept d = (Dept)context.getBean("dept");
System.out.println(d);
}
}
Please correct me if I am doing any thing wrong in it.
Spring is matching the emp variable name; if your beans were emp1 and emp2 you'd get an exception (unless you add a #Qualifier to the #AutoWired field).
You have defined a variable named as "emp" of Employee class which is same as the bean with id as "emp".Because of this spring don't get confused understanding which bean it has to inject.and if you change the bean id from "emp" to something else you will get an unsatisfied bean dependency exception. read more here
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>