I wrote below 2 Java classes for learning Spring, but getting FileNotFoundException after running the code. Please help me to resolve this issue.
Is it not taking the path of the XML file?
package com.javatpoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("xmlContext.xml");
//Resource resource=new ClassPathResource("xmlContext.xml");
//BeanFactory factory=new XmlBeanFactory(resource);
Student student = (Student)context.getBean("studentbean");
student.displayName();
}
}
2)
package com.javatpoint;
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void displayName() {
System.out.println("Name :"+name);
}
}
XML file:
<?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-3.0.xsd">
<bean id="studentbean" class="com.javatpoint.Student">
<property name="name" value="Vimal Jaiswal"></property>
</bean>
</beans>
Related
I am writing simple aspect with simple logging advice which will be called upon setter of class.
Below is code Snippet
AopMain.java
package com.example.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.example.test.model.Triangle;
import com.example.test.service.ShapeService;
public class AopMain {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
//ShapeService shapeService = context.getBean("shapeService", ShapeService.class);
//shapeService.getTriangle().setName("triangle");
Triangle triangle = new Triangle();
triangle.setName("triangle class");
System.out.println(triangle.getName());
}
}
Triangle.java
package com.example.test.model;
public class Triangle {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
System.out.println(name);
}
}
LoggingAspect.java
package com.example.test.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import com.example.test.model.Triangle;
#Component
#Aspect
public class LoggingAspect {
#Before("execution(public * *(..))")
public void LoggingAdvice(JoinPoint jPoint) {
System.out.println("Advice run. Get method is called " + jPoint.getTarget());
Triangle triangle = (Triangle) jPoint.getTarget();
}
#Before("args(name)")
public void test(String name) {
System.out.println("logging advice args " + name);
}
}
Output
triangle class
triangle class
spring.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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<!-- <bean id="triangle" class="com.example.test.model.Triangle">
<property name="name" value="Triangle Name"></property>
</bean> -->
<bean id="circle" class="com.example.test.model.Circle">
<property name="name" value="Circle Name"></property>
</bean>
<bean id="shapeService"
class="com.example.test.service.ShapeService" autowire="byType" />
<aop:aspectj-autoproxy />
<context:component-scan
base-package="com.example.test" />
</beans>
spring is working properly.
I do not understand why aspect is not gettting called.
please help me to understand this issue.
I'm trying to convert Csv data to Pojo using Apache Camel 2.24.1, but it is throwing exception.Can anyone help me to solve this issue.
CsvToPojoRoute.java
public class CsvToPojoRoute extends RouteBuilder {
public void configure() throws Exception {
DataFormat bindy = new BindyCsvDataFormat(com.tiger.puli.dto.Employee.class);
from("direct:start")
.unmarshal(bindy)
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
Message in = exchange.getIn();
List<Map<String,Object>> modelMap =
(List<Map<String,Object>>) in.getBody();
Employee emp = (Employee) modelMap.get(0).get(Employee.class.getCanonicalName());
System.out.println("EmployeeName:"+emp.getFirstName()+" "+emp.getLastName());
}
}).end();
}
Employee.java
#CsvRecord(separator = ",")
public class Employee implements Serializable {
#DataField(pos = 1,trim = true)
private String firstName;
#DataField(pos = 2)
private String lastName;
#DataField(pos = 3)
private String dept;
#DataField(pos = 4,trim = true)
private String fullTime;
}
Main.java
public static void main(String[] args) {
ApplicationContext springContext = new ClassPathXmlApplicationContext("classpath:camel-context.xml");
SpringCamelContext camelContext = springContext.getBean("camelcontextbean",SpringCamelContext.class);
try{
camelContext.start();
System.out.println("Started");
camelContext.addRoutes(springContext.getBean("CsvToPojoRoute", RoutesBuilder.class));
ProducerTemplate template = camelContext.createProducerTemplate();
System.out.println("ProducerTemplate");
template.sendBody("direct:start",
"john,doe,d1,true,city1,state1,1234");
}catch (Exception e){
System.out.println("Exception occured while biding csv to pojo:"+e.getMessage());
}
}
camel-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext lazyLoadTypeConverters="true" autoStartup="false" id="camelcontextbean" xmlns="http://camel.apache.org/schema/spring"/>
<bean id="CsvToPojoRoute" class="com.tiger.puli.config.CsvToPojoRoute" />
</beans>
It is returning "Exception occured while biding csv to pojo". Can I know what's the issue.
I am trying to integrate Jersey with Spring using maven webapp-archetype. When I get the object form the ApplicationContext I see my code executing, but when I try to use #Autowired it throws me NullPointerException. Following are the code snippets:
applicationContext.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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.pack.resource" />
<bean id="person" class="com.pack.resource.Person">
<property name="name" value="SomeNamexxxx" />
</bean>
Person.java
package com.pack.resource;
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person() {
}
}
Hello.java
package com.pack.resource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.springframework.beans.factory.annotation.Autowired;
import javax.ws.rs.core.MediaType;
import org.springframework.stereotype.Component;
#Component
#Path("/hello")
public class Hello {
#Autowired
Person person;
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getName() {
return person.getName();
}
}
But when I use ApplicationContext.getBean("person").getName() it gives me the actual value inside the bean property.
Why is #Autowired annotation not working as it should. Kindly help me.
TIA!
I am trying to learn AOP spring. so I have installed AspectJ plug in and created AspectJ project in Luna eclipse and here is snapshot of Project Explore:
[Project Explore][1] [1]: https://i.stack.imgur.com/el0TZ.jpg
and here is my codes:
AopMain.java
package org.koushik.javabrains;
import org.koushik.javabrains.service.ShapeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AopMain {
public static void main(String[] args) {
ApplicationContext ctx = new
ClassPathXmlApplicationContext("spring.xml");
ShapeService shapeService = ctx.getBean("shapeService",ShapeService.class);
System.out.println(shapeService.getCircle().getCircleName());
}
}
LoggingAspect.java
package org.koushik.javabrains.aspect;
import org.aspectj.lang.JoinPoint;
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 LoggingAspect {
#Before( "allCircleMethod()")
public void loggingAdvice(JoinPoint joinPoint){
System.out.println(joinPoint.toString());
}
//#Before("args(name)")
//public void stringArgumentMethods(String name){
// System.out.println("name: "+name);
//}
#Pointcut("execution(* get*())")
public void allGetters(){}
#Pointcut("within(org.koushik.javabrains.model.Circle)")
public void allCircleMethod(){}
}
Circle.java
package org.koushik.javabrains.model;
public class Circle {
private String circleName;
public String getCircleName() {
return circleName;
}
public void setCircleName(String circleName) {
this.circleName = circleName;
}
}
Triangle.java
package org.koushik.javabrains.model;
public class Triangle {
private String triangleName;
public String getTriangleName() {
return triangleName;
}
public void setTriangleName(String triangleName) {
this.triangleName = triangleName;
}
}
ShapeServices.java
package org.koushik.javabrains.service;
import org.koushik.javabrains.model.Circle;
import org.koushik.javabrains.model.Triangle;
public class ShapeService {
private Circle circle;
private Triangle triangle;
public Circle getCircle() {
return circle;
}
public void setCircle(Circle circle) {
this.circle = circle;
}
public Triangle getTriangle() {
return triangle;
}
public void setTriangle(Triangle triangle) {
this.triangle = triangle;
}
}
spring.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"
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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<bean name="triangle" class="org.koushik.javabrains.model.Triangle">
<property name="name" value ="Triangle name"></property>
</bean>
<bean name="circle" class="org.koushik.javabrains.model.Circle">
<property name="name" value ="Circle Name"></property>
</bean>
<bean name="shapeService" class="org.koushik.javabrains.service.ShapeService" autowire="byName"/>
<bean name ="loggingAspect" class ="org.koushik.javabrains.aspect.LoggingAspect"/>
</beans>
The code works fine without using in LoggingAspect.java:
#Before("args(name)")
public void stringArgumentMethods(String name){
System.out.println("name: "+name);
}
but when I add it, I will get the java.lang.stackOverflowError:
Exception in thread "main" java.lang.StackOverflowError
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
can anyone tell me why this happend? how can solve it?
From java docs,
StackOverFlowError - What:
Thrown when a stack overflow occurs because an application recurses
too deeply.
This means , memory (stack) is full and have no space to store further.
Why:
In most cases this situation is created by recursive/deep calling of methods.
In Your case, #Before("args(name)") - this line tries to find ALL methods with the argument "name", it find itself which leads to recursive call and the stackoverflow error.Because stringArgumentMethods(String name) also having the argument name
public void stringArgumentMethods(String name){
System.out.println("name: "+name);
}
How to Solve:
Either rewrite your AspectJ expression - #Before("args(name)")
Or
rename the argument like stringArgumentMethods(String name123)
i am not sure what i am doing wrong , i am trying to execute a stored-procedure using jdbc call but when ever i execute its hitting exception
java.lang.IllegalArgumentException: Property 'dataSource' is required .
Controller Class:
#Controller
public class GpsController {
#RequestMapping(value="h",method=RequestMethod.POST)
public void show(#ModelAttribute("PredefinedPath") PredefinedPath predefinedPath)
{
PredefinedPathService service=new PredefinedPathService();
//passing dto obj to service
boolean res= service.savePredefinedPath(predefinedPath);
}
DTO CLASS:
//Entity Class Getters and setters
public class PredefinedPath {
public int getPredefinedPath_Id() {
return PredefinedPath_Id;
}
public void setPredefinedPath_Id(int predefinedPath_Id) {
PredefinedPath_Id = predefinedPath_Id;
}
public String getPredefinedPath_Name() {
return PredefinedPath_Name;
}
public void setPredefinedPath_Name(String predefinedPath_Name) {
PredefinedPath_Name = predefinedPath_Name;
}
public String getSource() {
return Source;
}
public void setSource(String source) {
Source = source;
}
public String getDestination() {
return Destination;
}
public void setDestination(String destination) {
Destination = destination;
}
public String getEstimate_km() {
return Estimate_km;
}
public void setEstimate_km(String estimate_km) {
Estimate_km = estimate_km;
}
public double getSource_Latitude() {
return Source_Latitude;
}
public void setSource_Latitude(double source_Latitude) {
Source_Latitude = source_Latitude;
}
public double getSource_Longtitude() {
return Source_Longtitude;
}
public void setSource_Longtitude(double source_Longtitude) {
Source_Longtitude = source_Longtitude;
}
public double getDestination_Latitude() {
return Destination_Latitude;
}
public void setDestination_Latitude(double destination_Latitude) {
Destination_Latitude = destination_Latitude;
}
public double getDestination_Longtitude() {
return Destination_Longtitude;
}
public void setDestination_Longtitude(double destination_Longtitude) {
Destination_Longtitude = destination_Longtitude;
}
public String getEffectiveFromDate() {
return EffectiveFromDate;
}
public void setEffectiveFromDate(String effectiveFromDate) {
EffectiveFromDate = effectiveFromDate;
}
public String getEffectiveToDate() {
return EffectiveToDate;
}
public void setEffectiveToDate(String effectiveToDate) {
EffectiveToDate = effectiveToDate;
}
public int getStatus_Id() {
return Status_Id;
}
public void setStatus_Id(int status_Id) {
Status_Id = status_Id;
}
private int PredefinedPath_Id;
private String PredefinedPath_Name;
private String Source;
private String Destination;
private String Estimate_km;
private double Source_Latitude;
private double Source_Longtitude;
private double Destination_Latitude;
private double Destination_Longtitude;
private String EffectiveFromDate;
private String EffectiveToDate;
private int Status_Id;
}
DAO CLASS :
import javax.sql.DataSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import com.Ss.App.dto.PredefinedPath;
public class PredefinedPathDaoImpl {
private DataSource dataSource;
private SimpleJdbcCall jdbcCall;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public boolean savePredefined(PredefinedPath predefinedPathDto)
{
System.out.println("INSIDE DAO");
this.jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("PredefinedPath_Insert");
SqlParameterSource sqlParameterSource = new MapSqlParameterSource()
.addValue("PredefinedPath_Name", predefinedPathDto.getPredefinedPath_Name())
.addValue("Source", predefinedPathDto.getSource())
.addValue("Destination", predefinedPathDto.getDestination())
.addValue("Source_Latitude", predefinedPathDto.getSource_Latitude())
.addValue("Source_Longtitude", predefinedPathDto.getSource_Longtitude())
.addValue("Destination_Latitude", predefinedPathDto.getDestination_Latitude())
.addValue("Destination_Longtitude", predefinedPathDto.getDestination_Longtitude())
.addValue("EffectiveFromDate",null)
.addValue("EffectiveToDate",null)
.addValue("Status_Id", 4);
jdbcCall.execute(sqlParameterSource);
return true;
}
}
Service Class:
import com.Ss.App.dto.PredefinedPath;
import com.Ss.App.model.dao.PredefinedPathDaoImpl;
public class PredefinedPathService {
PredefinedPathDaoImpl predefinedPathDao=new PredefinedPathDaoImpl();
public boolean savePredefinedPath(PredefinedPath predefinedPathdto)
{
boolean result=predefinedPathDao.savePredefined(predefinedPathdto);
return result;
}
}
Spring Config:
<?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="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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.Ss.App"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- Definition for studentJDBCTemplate bean -->
<bean id="PredefinedPathDaoImpl" class="com.Ss.App.model.dao.PredefinedPathDaoImpl">
<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>
<property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=test"></property>
<property name="username" value="sa"></property>
<property name="password" value="pass"></property>
</bean>
<mvc:annotation-driven />
</beans>
web.config
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>SpringAngularjs</display-name>
<welcome-file-list>
<welcome-file>page.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
The service in your controller is not managed by Spring as you instantiate it yourself.
That's why the datasource is not set in this bean.
Replace :
#Controller
public class GpsController {
#RequestMapping(value="h",method=RequestMethod.POST)
public void show(#ModelAttribute("PredefinedPath") PredefinedPath predefinedPath)
{
PredefinedPathService service=new PredefinedPathService();
//passing dto obj to service
boolean res = service.savePredefinedPath(predefinedPath);
}
}
By
#Controller
public class GpsController {
#Autowired
private PredefinedPathService service;
#RequestMapping(value="h",method=RequestMethod.POST)
public void show(#ModelAttribute("PredefinedPath") PredefinedPath predefinedPath)
{
//passing dto obj to service
boolean res = service.savePredefinedPath(predefinedPath);
}
}