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;
}
Related
MY Spring AOP programm is not working as Expected.
I created simple AOP annotation program below but the output is not what I thought.
Programm :
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"
xmlns:aop = "http://www.springframework.org/schema/aop"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<aop:aspectj-autoproxy/>
<bean id="student" class="com.surajhome.practice.spring.Student" >
<property name="name" value="Suraj Kudale"></property>
<property name="age" value="27"></property>
</bean>
<bean id="logging" class="com.surajhome.practice.spring.Logging"></bean>
</beans>
Student.java
package com.surajhome.practice.spring;
public class Student {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
String name;
int age;
}
Logging.Java
package com.surajhome.practice.spring;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class Logging {
#Pointcut("execution(* com.surajhome.practice.spring.*.*(..) )")
public void selectAll()
{
}
#After("selectAll()")
public void afterAdvice()
{
System.out.println("After Advice called");
}
#Before("selectAll()")
public void beforeAdvice()
{
System.out.println("Before Advice called");
}
public void afterReturningAdvice()
{
System.out.println("After Returning Advice called");
}
public void afterThrowingException()
{
System.out.println("After Exception Advice called");
}
}
MainApp.java
package com.surajhome.practice.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext appContext=new ClassPathXmlApplicationContext("Beans.xml");
Student std=(Student) appContext.getBean("student");
System.out.println(std.getName());
System.out.println(std.getAge());
}
}
output :
Before Advice called
After Advice called
Suraj Kudale
Before Advice called
After Advice called
27
It should be :
Before Advice called
Suraj Kudale
After Advice called
Before Advice called
27
After Advice called
Think of the flow that happens when you call the System.out.println(std.getName());, first #Before method of the get name is called then get name returns a value and #After is called only then System.out.println gets the string and prints it
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>
I am trying to use Mongo Template with spring but it gives InvalidDataAccessApiUsageException
My Main Class is
package com.spring.mongodb.main;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.spring.mongodb.model.Person;
public class SpringDataMongoDBMain {
public static final String DB_NAME = "mydb";
public static final String PERSON_COLLECTION = "mycol";
public static final String MONGO_HOST = "localhost";
public static final int MONGO_PORT = 27017;
public static void main(String[] args) {
try{
Mongo mongo = new MongoClient(MONGO_HOST, MONGO_PORT);
System.out.println("Connected to MongoDB");
MongoOperations mongoOps = new MongoTemplate(mongo, DB_NAME);
System.out.println("Connected to database");
Person p = new Person("100", "ABC", "GRG PQR");
mongoOps.createCollection(PERSON_COLLECTION);
mongoOps.insert(p, PERSON_COLLECTION);
}catch(Exception e){
e.printStackTrace();
}
}
}
My Model Class is:
package com.spring.mongodb.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "person")
public class Person {
#Id
private String id;
private String name;
private String address;
public Person() {
}
public Person(String i, String n, String a) {
this.id = i;
this.name = n;
this.address = a;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Override
public String toString() {
return id + "::" + name + "::" + address;
}
}
and my Spring.xml is
<?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:mongo="http://www.springframework.org/schema/data/mongo"
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-4.0.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd">
<mongo:mongo host="localhost" port="27017" id="mongo" />
<mongo:db-factory dbname="mydb" mongo-ref="mongo"
id="mongoDbFactory" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<bean id="personDAO" class="com.journaldev.spring.mongodb.dao.PersonDAOImpl">
<constructor-arg name="mongoOps" ref="mongoTemplate" />
</bean>
</beans>
When I run the above code it gives following error :
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/dao/InvalidDataAccessApiUsageException
at com.spring.mongodb.main.SpringDataMongoDBMain.main(SpringDataMongoDBMain.java:21)
Caused by: java.lang.ClassNotFoundException: org.springframework.dao.InvalidDataAccessApiUsageException
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
... 1 more
I have added following jars:
mongodb-driver-3.1.1.jar
mongodb-driver-core-3.1.1.jar
spring-core-4.2.3.RELEASE.jar
spring-data-mongodb-1.6.1.RELEASE.jar
spring-data-commons-core-1.4.1.RELEASE.jar
I tried debuging the code it shows error when it comes to MongoOperations object creation and terminates.What I am doing wrong??
You're missing some jars (spring-tx, spring-beans, spring-context, spring-expression, etc..)
Have a look at maven to manage your dependencies
Hello guys so i have a bit issue. I wrote a simple rest application using spring framework. I was able to post and get the response in json but now i want to have the option of displaying both json and xml format. Now i'm getting error 406 when trying to display the format in xml. I already included the converter in dispatcher but having trouble displaying in xml format. Please i'm i missing soemthing. Also included the dependency in maven:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
Below is my dispatcher-servlet.xml which loads the controller. :
<?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:mvc-annotation="http://www.springframework.org/schema/mvc"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="edu.sjsu.cmpe275.lab2.controller" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" >
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
</list>
</property>
</bean>
<mvc:annotation-driven/>
</beans>
below is my method in the controller upon entering the url when trying to produce the output in xml:
#RequestMapping(value="player/{id}", method=RequestMethod.GET, params="format=xml", produces=MediaType.APPLICATION_XML_VALUE)
#ResponseBody
public ResponseEntity<?> inXML(#PathVariable("id")long id) {
Person person = personImpl.findById(id);
if(person!=null){
return new ResponseEntity<Person>(person, HttpStatus.OK);
}
else
return new ResponseEntity<String>("Id doesn't exist", HttpStatus.NOT_FOUND);
}
Person POJO:
public class Person {
#Id
#Column(name="person_Id")
#GeneratedValue
private long id;
#Column(unique = true)
private String email;
private String first_name, last_name, description;
//#Embedded
private Address address;
#ManyToOne(cascade = CascadeType.ALL)
private Organization organization;
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name="Friends")
Collection<Person> persons = new ArrayList<Person>();
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
public Person() {}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
package com.bpp.beans;
public class EmpBean {
String name;
String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void initempbean()
{
System.out.println("inside initempbean");
}
public void destroyempbean()
{
System.out.println("inside destroyempbean");
}
}
package com.bpp.beans;
public class Person {
String name;
String id;
EmpBean empBean;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public EmpBean getEmpBean() {
return empBean;
}
public void setEmpBean(EmpBean empBean) {
this.empBean = empBean;
}
public void initperson()
{
System.out.println("inside init personnnnnnn");
}
public void destroyperson()
{
System.out.println("inside destroy personnnn");
}
}
package com.bpp.beans;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class EmpPostProcessor implements BeanPostProcessor {
#Override
public Object postProcessAfterInitialization(Object bean, String arg1)
throws BeansException {
System.out.println("inside bean pp after initialization");
return null;
}
#Override
public Object postProcessBeforeInitialization(Object bean, String arg1)
throws BeansException {
System.out.println("inside bean pp before initialization");
return null;
}
}
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean class="com.bpp.beans.EmpPostProcessor"/>
<bean id="emp" class="com.bpp.beans.EmpBean" init-method="initempbean" destroy-method="destroyempbean">
<property name="name" value="sanjay"/>
<property name="id" value="44"/>
</bean>
<bean id="person" class="com.bpp.beans.Person" init-method="initperson" destroy-method="destroyperson">
<property name="name" value="sanju"/>
<property name="id" value="77"/>
<property name="empBean" ref="emp"/>
</bean>
</beans>
package com.bpp.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.bpp.beans.Person;
public class BppMain {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("com/bpp/commons/application-context.xml");
Person obj=context.getBean("person",Person.class);
System.out.println("the value of name is:"+obj.getName());
}
}
The exception is null pointer exception,while creating emp bean
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'emp' defined in class path resource [com/bpp/commons/application-context.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.bpp.main.BppMain.main(BppMain.java:12)
Caused by: java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
... 12 more
In the Spring doc is written for postProcessAfterInitialization and postProcessBeforeInitialization :
Returns:
the bean instance to use, either the original or a wrapped one
Since you do nothing in these methods you should return the Object passed as a parameter, which is the instance of the bean.