How to Autowired properties file to Environment variable? - maven

My maven project fail to autowired my properties file into Environment variable. I am using spring 4.2.3.
This is the error when I run maven:test
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#57e1b0c: startup date [Sun Dec 20 08:55:34 PST 2015]; root of context hierarchy
Dec 20, 2015 8:55:34 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from URL [file:/home/bryan-1/workspace/2015dec_riot/test/target/test-classes/applicationContext.xml]
Dec 20, 2015 8:55:34 AM org.springframework.context.support.PropertySourcesPlaceholderConfigurer loadProperties
INFO: Loading properties file from class path resource [application.it.properties]
Dec 20, 2015 8:55:34 AM org.springframework.context.support.ClassPathXmlApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'JMSProperties' defined in file [/home/bryan-1/workspace/2015dec_riot/test/target/classes/test/JMSProperties.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [test.JMSProperties$$EnhancerBySpringCGLIB$$b873400b]: Constructor threw exception; nested exception is java.lang.NullPointerException
This is my applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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"
xmlns:context="http://www.springframework.org/schema/context">
<context:component-scan base-package="test" />
<context:property-placeholder location="classpath:/application.it.properties" />
<!-- bean definitions here -->
</beans>
This is my properties class:
#Configuration
public class JMSProperties {
....
#Autowired
private Environment env;
public JMSProperties() {
....
}
....
}
This is the Test case generated by Maven by default:
public class AppTest
extends TestCase
{
#Autowired
JMSProperties properties;
private static final Logger logger = LoggerFactory.getLogger(AppTest.class);
AbstractApplicationContext context = new ClassPathXmlApplicationContext("classpath*:/applicationContext.xml");
/**
* Create the test case
*
* #param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* #return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
logger.info(properties.getMatchMakerPassword());
}
}
My Dependences:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<!-- logging framework dependencies -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-ext</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.2</version>
</dependency>
</dependencies>

Since the exception is a NPE in the constructor of JMSProperties, it would help to know what is your code there. Your post if not very helpful:
public JMSProperties() {
....
}
My guess is that you try to use env in there. At this point env in null, because spring has to instantiate the class first, and then inject the fields. Hence the NPE.

Related

Unable to use Spring cloud to connect with AWS SES

I have made a very simple maven project using Spring Boot. I am trying to connect with AWS SES using Spring cloud. While running the project, I am getting following error:
No valid instance id defined
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.cloud.aws.core.env.ResourceIdResolver.BEAN_NAME': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stackResourceRegistryFactoryBean' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.aws.core.env.stack.config.StackResourceRegistryFactoryBean]: Factory method 'stackResourceRegistryFactoryBean' threw exception; nested exception is java.lang.IllegalArgumentException: No valid instance id defined
I am showing snippets of files in use:
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-aws</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-ses</artifactId>
<version>1.11.505</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
SimpleMailAutoConfig.java
#Configuration
public class SimpleMailAutoConfig {
#Bean
public AmazonSimpleEmailService amazonSimpleEmailService(AWSCredentialsProvider credentialsProvider) {
return AmazonSimpleEmailServiceClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion(Regions.US_EAST_1).build();
}
#Bean
public MailSender mailSender(AmazonSimpleEmailService ses) {
return new SimpleEmailServiceMailSender(ses);
}
}
MailSendingService.java
#Service
public class MailSendingService {
#Autowired
private MailSender mailSender;
public void sendMailMessage() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom("foo#bar.com");
simpleMailMessage.setTo("example#test.com");
simpleMailMessage.setSubject("test subject");
simpleMailMessage.setText("test content");
this.mailSender.send(simpleMailMessage);
}
}
Application.java
#SpringBootApplication
#ComponentScan("com.example")
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
application.properties
cloud.aws.credentials.accessKey=${MyAccessKey}
cloud.aws.credentials.secretKey=${MySecretKey}
cloud.aws.region.static=us-east-1
I am not trying to connect to any EC2 instance. Not able to find any proper documentation for using spring cloud for SES
You've almost got it, you're just missing one more configuration flag to stop that exception creeping in.
Add cloud.aws.stack.auto = false to your application.properties file thus it will not enable the automatic stack name detection for the application.
You can read up more about it in the docs: http://cloud.spring.io/spring-cloud-aws/spring-cloud-aws.html#_cloudformation_configuration_in_spring_boot
Using the response of #Chris-Turner you can add a VM option to run your app locally:
-Dcloud.aws.stack.auto=false

Can't solve this issue UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl

i've tried alot to fix this issue but couldn't. I find, if we use "abstractBinder" then this could be fix but once i've my Binder in place, i start having 404 error.
UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl
Please help
My Resource:
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.walmart.services.helpers.IUserService;
import com.walmart.services.helpers.ServicesTest;
#Path("/sayHello")
public class ControllerTest {
#Inject
private IUserService service;
#Inject
private ServicesTest service2;
#GET
#Path("/{name}")
#Produces(MediaType.TEXT_PLAIN)
public String method(#PathParam("name") String msg) {
return service.method() + " msg";
}
#GET
#Path("/v2/{name}")
#Produces(MediaType.TEXT_PLAIN)
public String method2(#PathParam("name") String msg) {
return service2.method() + " msg";
}
}
My resource configuration file:
#ApplicationPath("/rest/*")
public class ResourceConfiguration extends ResourceConfig {
public ResourceConfiguration() {
//register(new MyBinder());
this.packages(true, "com.walmart.services.*");
}
}
My Binder [ if in place ]
public class MyBinder extends AbstractBinder
{
#Override
protected void configure() {
// TODO Auto-generated method stub
bind(new ServicesTest()).to(ServicesTest.class);
// bind(UserServiceImpl.class).to(IUserService.class).in(RequestScoped.class);
}
}
Services:
IUserService and its implementation
public interface IUserService {
public String method();
}
public class UserServiceImpl implements IUserService {
#Inject
public UserServiceImpl() {
System.out.println("test");
}
#Override
public String method() {
return "Welcome ";
}
}
Other
public class ServicesTest {
public ServicesTest() {
System.out.println("created ");
}
public String method() {
return "Welcome";
}
}
WEbXML
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>com.walmart.learning.javaee</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Now, i can access my resource using
http://localhost:8080/javaeeLearning/rest/sayHello/h
Which gives me below errors
SEVERE: Servlet.service() for servlet [com.walmart.configuration.ResourceConfiguration] in context with path [/javaeeLearning] threw exception [A MultiException has 4 exceptions. They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=IUserService,parent=ControllerTest,qualifiers={},position=-1,optional=false,self=false,unqualified=null,2007960340)
2. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=ServicesTest,parent=ControllerTest,qualifiers={},position=-1,optional=false,self=false,unqualified=null,10615079)
3. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.walmart.services.rest.controller.ControllerTest errors were found
4. java.lang.IllegalStateException: Unable to perform operation: resolve on com.walmart.services.rest.controller.ControllerTest
] with root cause
And to resolve, i uncomment my Binder in Resource configuration
then i start having 404.
Please help....
Other details;
Pom
<name>javaeeLearning</name>
<properties>
<maven.compiler.source>10</maven.compiler.source>
<maven.compiler.target>10</maven.compiler.target>
<jaxrs.version>2.0.1</jaxrs.version>
<jersey2.version>2.23</jersey2.version>
<jersey2.gf.cdi.version>2.14</jersey2.gf.cdi.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax/javaee-api -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>${jaxrs.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-war-plugin -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</dependency>
<!-- Jersey2.x Dependencies -->
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-server -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey2.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-common -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>${jersey2.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-client -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey2.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey2.version}</version>
</dependency>
<!-- Jersey2.x Dependency injection -->
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.inject/jersey-hk2 -->
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.27</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.activation/activation -->
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jaxb/jaxb-core -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.4.0-b180830.0438</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey2.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.containers.glassfish/jersey-gf-cdi -->
<dependency>
<groupId>org.glassfish.jersey.containers.glassfish</groupId>
<artifactId>jersey-gf-cdi</artifactId>
<version>${jersey2.gf.cdi.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.enterprise/cdi-api -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
Make your JAX-RS resource a CDI bean like this:
#Path("/sayHello")
#RequestScoped
public class ControllerTest {
Then you don't need the Binder and injection should work.
You could set bean discovery mode to all in beans.xml:
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
or annatate UserServiceImpl with an scope annotation (like #Dependent)

Spring c-namespace issue - Constructor argument '_street' specifies an invalid integer

I am trying out the use of c-namespace while injecting literal values into a constructor. I am running into an issue if I refer to the constructor argument by its name. If I refer to it by the position (i.e. 0,1,2...) it works perfectly fine.
I have set the variable debugging check in eclipse (I am using STS) - Windows > Preferences > Java > Compiler > Add variable attributes to generated class files but I still see the same issue
Below is my code -
Interface
package com.nilaysundarkar.spring.demos;
public interface Person {
public void speak();
}
Implementation
package com.nilaysundarkar.spring.demos;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.inject.Named;
#Component
#Named("Russland")
public class Russian implements Person, BeanNameAware {
private String language = "Russian";
private Address address;
#Autowired
public Russian(Address address){
this.address = address;
}
public void speak() {
System.out.println("I am a Person. I speak " + language + ".");
System.out.println("I stay at " + address + ".");
}
public void setBeanName(String beanName) {
System.out.println(beanName + " has been initialized.");
}
}
Address class
package com.nilaysundarkar.spring.demos;
public class Address {
private String street;
public Address(String street){
this.street = street;
}
public String toString(){
return street;
}
}
Bootstrapping the context -
package com.nilaysundarkar.spring.demos;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext("beans.xml");
Person person = context.getBean(Person.class);
person.speak();
((FileSystemXmlApplicationContext) context).close();
}
}
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.nilaysundarkar.spring.demos"/>
<!-- Works -->
<!--<bean id="address" class="com.nilaysundarkar.spring.demos.Address" c:_0="200 Baker Street" />-->
<!-- Does'nt Work -->
<bean id="address" class="com.nilaysundarkar.spring.demos.Address" c:_street="200 Baker Street" />
</beans>
Error when run with c:_street -
Mar 25, 2017 1:39:44 PM org.springframework.context.support.FileSystemXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext#179d3b25: startup date [Sat Mar 25 13:39:44 EDT 2017]; root of context hierarchy
Mar 25, 2017 1:39:44 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [C:\Users\Nilay\Documents\workspace-sts-3.8.3.RELEASE\demos\beans.xml]
Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Constructor argument '_street' specifies an invalid integer
Offending resource: file [C:\Users\Nilay\Documents\workspace-sts-3.8.3.RELEASE\demos\beans.xml]
at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:70)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:72)
at org.springframework.beans.factory.xml.SimpleConstructorNamespaceHandler.decorate(SimpleConstructorNamespaceHandler.java:111)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.decorateIfRequired(BeanDefinitionParserDelegate.java:1448)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.decorateBeanDefinitionIfRequired(BeanDefinitionParserDelegate.java:1427)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.decorateBeanDefinitionIfRequired(BeanDefinitionParserDelegate.java:1415)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.processBeanDefinition(DefaultBeanDefinitionDocumentReader.java:301)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:190)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:169)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:142)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:94)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:508)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:392)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:252)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:613)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:514)
at org.springframework.context.support.FileSystemXmlApplicationContext.<init>(FileSystemXmlApplicationContext.java:140)
at org.springframework.context.support.FileSystemXmlApplicationContext.<init>(FileSystemXmlApplicationContext.java:84)
at com.nilaysundarkar.spring.demos.App.main(App.java:9)
When run with c:_0
Mar 25, 2017 1:42:35 PM org.springframework.context.support.FileSystemXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext#179d3b25: startup date [Sat Mar 25 13:42:35 EDT 2017]; root of context hierarchy
Mar 25, 2017 1:42:35 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [C:\Users\Nilay\Documents\workspace-sts-3.8.3.RELEASE\demos\beans.xml]
Mar 25, 2017 1:42:36 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Russland has been initialized.
I am a Person. I speak Russian.
I stay at 200 Baker Street.
Mar 25, 2017 1:42:36 PM org.springframework.context.support.FileSystemXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.FileSystemXmlApplicationContext#179d3b25: startup date [Sat Mar 25 13:42:35 EDT 2017]; root of context hierarchy
pom.xml -
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.nilaysundarkar.spring</groupId>
<artifactId>demos</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
</dependencies>
</project>
The correct way would be to use c:street and not c:_street, as the value after c: prefix must match the constructor parameter name.

I have an application to run with spring boot. I need to use hibernate with it. I get this exception

I have an application to run with spring boot. I need to use hibernate with it. I get this exception. I'm not sure about the configuration files I should have. Since I have searched so much and new to spring: I have pom.xml, and I don't know whether I should have web.xml or not. I need to get it work as soon as possible. this is my exception thrown:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'userController' defined in file
[C:\Users\Mehrnaz\JEEKeplerWorkspace\rest-stack\target\classes\com\jl\crm\contoller\UserController.class]:
Unsatisfied dependency expressed through constructor argument with index 0 of type
[com.jl.crm.services.CrmService]: : Error creating bean with name 'jpaCrmService' defined in file
[C:\Users\Mehrnaz\JEEKeplerWorkspace\rest-stack\target\classes\com\jl\crm\services\JpaCrmService.class]:
Unsatisfied dependency expressed through constructor argument with index 0 of type
[com.jl.crm.repository.CustomerRepository]: : No qualifying bean of type
[com.jl.crm.repository.CustomerRepository] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {};
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [com.jl.crm.repository.CustomerRepository]
found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {};
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'jpaCrmService' defined in file
[C:\Users\Mehrnaz\JEEKeplerWorkspace\rest-stack\target\classes\com\jl\crm\services\JpaCrmService.class]:
Unsatisfied dependency expressed through constructor argument with index 0 of type
[com.jl.crm.repository.CustomerRepository]: : No qualifying bean of type
[com.jl.crm.repository.CustomerRepository] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
=======
my pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>rest-stack</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- other project -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring3</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.1.Final</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.jl.crm.services.ServiceConfiguration</param-value>
</context-param>
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<servlet-name>appServlet</servlet-name>
</filter-mapping>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I have log4j.properties:
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Root logger option
log4j.rootLogger=DEBUG,stdout
and Application.properties:
#
## Database configuration
#
spring.datasource.url= jdbc:mysql://localhost:3307/spring
spring.datasource.username= spring
spring.datasource.password= spring
spring.datasource.driverClassName= com.mysql.jdbc.Driver
spring.view.prefix=/WEB-INF/jsp/
spring.view.suffix=.jsp
this is service.configuration class, that I think may have problem:
#ComponentScan
#Configuration
#EnableJpaRepositories
public class ServiceConfiguration {
public static final String CRM_NAME = "crm";
/**
* The root directory to which all uploads for the application are uploaded.
*/
public static final File CRM_STORAGE_DIRECTORY = new File(
System.getProperty("user.home"), CRM_NAME);
/**
* Things are first uploaded by the application server to this directory. it's a sort
* of staging directory
*/
public static final File CRM_STORAGE_UPLOADS_DIRECTORY = new File(CRM_STORAGE_DIRECTORY, "uploads");
/**
* When a profile photo is uploaded, the resultant, completely uploaded image is
* stored in this directory
*/
public static final File CRM_STORAGE_PROFILES_DIRECTORY = new File(CRM_STORAGE_DIRECTORY, "profiles");
#PostConstruct
protected void setupStorage() throws Throwable {
File[] files = {CRM_STORAGE_DIRECTORY, CRM_STORAGE_UPLOADS_DIRECTORY, CRM_STORAGE_PROFILES_DIRECTORY};
for (File f : files) {
if (!f.exists() && !f.mkdirs()) {
String msg = String.format("you must create the profile photos directory ('%s') " +
"and make it accessible to this process. Unable to do so from this process.", f.getAbsolutePath());
throw new RuntimeException(msg);
}
}
}
#Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory( JpaVendorAdapter adapter, DataSource dataSource) {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setPackagesToScan(User.class.getPackage().getName());
emf.setDataSource(dataSource);
emf.setJpaVendorAdapter(adapter);
return emf;
}
#Bean
PlatformTransactionManager transactionManager( EntityManagerFactory emf) {
return new JpaTransactionManager(emf);
}
#Configuration
#Profile({"default", "test"})
static class DefaultDataSourceConfiguration {
private Log log = LogFactory.getLog(getClass());
#PostConstruct
protected void setupTestProfileImages() throws Exception {
long userId = 5;
File profilePhotoForUser5 = new File(ServiceConfiguration.CRM_STORAGE_PROFILES_DIRECTORY, Long.toString(userId));
if (!profilePhotoForUser5.exists()) {
// copy the profile photo back
String pathForProfilePhoto = "/sample-photos/spring-dog-2.png";
ClassPathResource classPathResource = new ClassPathResource(pathForProfilePhoto);
Assert.isTrue(classPathResource.exists(), "the resource " + pathForProfilePhoto + " does not exist");
OutputStream outputStream = new FileOutputStream(profilePhotoForUser5);
InputStream inputStream = classPathResource.getInputStream();
try {
IOUtils.copy(inputStream, outputStream);
} finally {
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
}
log.debug("setup photo " + profilePhotoForUser5.getAbsolutePath() + " for the sample user #" + Long.toString(userId) + "'s profile photo.");
}
if (!profilePhotoForUser5.exists()) {
throw new RuntimeException("couldn't setup profile photos at " + profilePhotoForUser5.getAbsolutePath() + ".");
}
}
}
}
#ComponentScan
#Configuration(basePackages = {"<Specify your base package here>"})
#EnableJpaRepositories
public class ServiceConfiguration {
---
}
you missed base package name for the componentscan annotation.

jersey-spring3 instantiating Spring-managed bean (null!)

I first want to point out that this is by and large the biggest problem in terms of time wasted that I have ever dealt with in my career. (Over two days straight now with essentially 0 progress.) Every single "work-around" or "solution" I have attempted hasn't worked, so I am blocked and pretty desperate for some assistance.
The problem in a nutshell is that Jersey/HK2 seems to always instantiate my Spring-managed beans AFTER they have already been instantiated by Spring, which tells me that jersey-spring3 is not doing its job, or at least not with my current setup (or any of the ~50 permutations of setups I have tried thus far.)
Note that when I use an empty constructor, those resource fields are null at run-time.
I do not understand why my current setup doesn't work as I am essentially copying this online example
Any help is more than appreciated!!
Configuration
- - - - - pom.xml - - - - -
<!-- ... -->
<dependencies>
<!-- Spring Dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument-tomcat</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-parent</artifactId>
<version>${spring.version}</version>
<classifier>tests</classifier>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.version}</version>
<classifier>tests</classifier>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-acl</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-support</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- / Spring Dependencies -->
<!-- API dependencies -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-processing</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<!-- / API dependencies -->
<!-- ... -->
</dependencies>
<!-- ... -->
<properties>
<!-- ... -->
<spring.version>3.0.5.RELEASE</spring.version>
<jersey.version>2.4.1</jersey.version>
<gson.version>2.2.4</gson.version>
<!-- ... -->
</properties>
<!-- ... -->
- - - - - web.xml - - - - -
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/beans.xml</param-value>
</context-param>
<!-- ... -->
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>fubar.rest.FubarJerseyApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<!-- ... -->
</web-app>
- - - - - beans.xml (Context Configuration) - - - - -
<?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-2.5.xsd">
<!-- ... -->
<!-- beans-outbound-api has configuration for spring-jersey3 to work properly -->
<import resource="beans-api.xml" />
</beans>
- - - - - beans-api.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"
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">
<!-- Services -->
<bean id="locationServiceV1" class="fubar.rest.v1.services.location.impl.LocationServiceV1" />
<bean id="locationServiceV2" class="fubar.rest.v2.services.location.impl.LocationServiceV2" />
<bean id="viewServiceV1" class="fubar.rest.v1.services.view.impl.ViewServiceV1" />
<bean id="viewServiceV2" class="fubar.rest.v2.services.view.impl.ViewServiceV2" />
<!-- Resources -->
<bean class="fubar.rest.resources.location.impl.LocationResource">
<constructor-arg index="0" ref="locationServiceV1" />
<constructor-arg index="1" ref="locationServiceV2" />
</bean>
<bean class="fubar.rest.resources.view.impl.ViewResource">
<constructor-arg index="0" ref="viewServiceV1" />
<constructor-arg index="1" ref="viewServiceV2" />
</bean>
</beans>
Code
- - - - - Resource (JAX-RS) - - - - -
#Path(RESTLocationResourceV1.PathFields.PATH_ROOT)
#Produces({V1_JSON, APPLICATION_JSON})
public class LocationResource
extends ResourceBase<LocationResource, ILocationServiceV1, ILocationServiceV2> {
private static final Logger logger = Logger.getLogger(LocationResource.class);
#Inject
public LocationResource(final LocationServiceV1 v1Loc, final LocationServiceV2 v2Loc) {
super(v1Loc, v2Loc);
logger.info(format(Messages.INF_INSTANTIATED, "LocationResource"));
}
#GET
#Path(PathFields.SUBPATH_LIST)
public LocationListV1 listV1(#HeaderParam(HEADER_API_KEY) String apiKey)
throws ApplicationException {
// Implementation
}
#GET
#Path(PathFields.SUBPATH_SEARCH)
public LocationListV1 searchV1(#HeaderParam(HEADER_API_KEY) String apiKey,
#QueryParam(QueryFields.QUERY) String likeText) throws ApplicationException {
// Implementation
}
}
- - - - - Service (Spring Bean) - - - - -
public class LocationServiceV1 extends ServiceBaseV1<LocationBean, LocationV1, LocationListV1>
implements
ILocationServiceV1 {
#Autowired
private LocationDao daoLoc;
public LocationServiceV1() {
super(new LocationBeanToJsonTranslatorV1());
}
#Override
public LocationListV1 listV1() throws ApplicationException {
// Implementation
}
#Override
public LocationListV1 searchV1(String likeText) throws ApplicationException {
// Implementation
}
}
(Essentially the same for version 2)
- - - - - Application (Jersey) - - - - -
public class FubarJerseyApplication extends ResourceConfig {
private static final class Messages {
static final String INF_STARTING_APPLICATION = "Starting %s!";
}
private static final Logger logger = Logger.getLogger(FubarJerseyApplication.class);
public FubarJerseyApplication() {
packages("fubar.rest");
logger.info(format(Messages.INF_STARTING_APPLICATION, this.getClass().getName()));
}
}
Invocation (Client)
curl http://my-ip-address/fubar/api/location/list
(500 Internal Server Error)
Error (Server)
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object
available for injection at Injectee(requiredType=LocationServiceV1,parent=
LocationResource,qualifiers={}),position=0,optional=false,self=false,
unqualified=null,344016971)
at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)
at org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:208)
at org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:225)
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:329)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:456)
at org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:158)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2350)
at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:612)
at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:597)
at org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:173)
at org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:185)
at org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:103)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:128)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:131)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:131)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:131)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:131)
at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:110)
at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:65)
at org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:250)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:318)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:236)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:983)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:361)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at fubar.server.springframework.SessionFilter.doFilter(SessionFilter.java:44)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at fubar.server.springframework.loader.ContextLoaderHttpInterceptor$LoaderState.filter(ContextLoaderHttpInterceptor.java:75)
at fubar.server.springframework.loader.ContextLoaderHttpInterceptor$StartedState.filter(ContextLoaderHttpInterceptor.java:120)
at fubar.server.springframework.loader.ContextLoaderHttpInterceptor.doFilter(ContextLoaderHttpInterceptor.java:62)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.jk.server.JkCoyoteHandler.invoke(JkCoyoteHandler.java:190)
at org.apache.jk.common.HandlerRequest.invoke(HandlerRequest.java:311)
at org.apache.jk.common.ChannelSocket.invoke(ChannelSocket.java:776)
at org.apache.jk.common.ChannelSocket.processConnection(ChannelSocket.java:705)
at org.apache.jk.common.ChannelSocket$SocketConnection.runIt(ChannelSocket.java:898)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:690)
at java.lang.Thread.run(Thread.java:662)
API Log
Dec 10, 2013 13:36:28 INFO [main] fubar.rest.FubarJerseyApplication
- Starting fubar.rest.FubarJerseyApplication!
Dec 10, 2013 13:38:06 INFO [pool-1-thread-1] resources.location.impl.LocationResource
- LocationResource has been instantiated
Dec 10, 2013 13:38:06 INFO [pool-1-thread-1] resources.view.impl.ViewResource
- ViewResource has been instantiated
Update -- found this:
Catalina Log
Dec 10, 2013 1:36:42 PM org.glassfish.jersey.server.ApplicationHandler initialize
INFO: Initiating Jersey application, version Jersey: 2.4.1 2013-11-08 12:08:47...
Dec 10, 2013 1:36:43 PM org.glassfish.jersey.server.spring.SpringComponentProvider initialize
SEVERE: Spring context lookup failed, skipping spring component provider initialization.
Dec 10, 2013 1:38:00 PM com.sun.xml.bind.v2.runtime.reflect.opt.Injector inject
... so the ApplicationContext isn't found in SpringComponentProvider#initialize.
What's loading first? Spring or Jersey? It could be that your Spring context isn't initialized when SpringComponentProvider calls WebApplicationContextUtils.getWebApplicationContext(sc);. Try using Spring's ContextLoaderListener so that Spring does its initialization right after the app is deployed.
I ran into a lot of the same issues that you're experiencing with the jersey-spring3 library. It had problems finding my Spring ApplicationContext (looks like this is where you're stuck) and it blew up injecting setters that took a generic parameter as an argument.
If you get past the app context issue, I don't think what you have will work anyway. You defined the ViewResource and LocationResource beans in XML. From what I can tell, Jersey will only get the resource instance from Spring if the the resource class is annotated with #Component. Take a look at org.glassfish.jersey.server.spring.SpringComponentProvider, specifically component.isAnnotationPresent(Component.class):
// detect JAX-RS classes that are also Spring #Components.
// register these with HK2 ServiceLocator to manage their lifecycle using Spring.
#Override
public boolean bind(Class<?> component, Set<Class<?>> providerContracts) {
if (ctx == null) {
return false;
}
if(component.isAnnotationPresent(Component.class)) {
DynamicConfiguration c = Injections.getConfiguration(locator);
String[] beanNames = ctx.getBeanNamesForType(component);
if(beanNames == null || beanNames.length != 1) {
LOGGER.severe(LocalizationMessages.NONE_OR_MULTIPLE_BEANS_AVAILABLE(component));
return false;
}
String beanName = beanNames[0];
ServiceBindingBuilder bb = Injections.newFactoryBinder(new SpringComponentProvider.SpringManagedBeanFactory(ctx, locator, beanName));
bb.to(component);
Injections.addBinding(bb, c);
c.commit();
LOGGER.config(LocalizationMessages.BEAN_REGISTERED(beanName));
return true;
}
return false;
}
An unrelated issue was that we also wanted to move all of our JAX-RS annotations to interfaces. Whenever I tried it, I got "Could not find a suitable constructor for com.foo.ResourceInterface".
In the end, I solved all of my issues by not using jersey-spring3 and rolling my own Jersey to Spring connector. Here's what I did:
Configured all of my resources as regular Spring beans. You can use XML if you want.
In my Application, I added bindings to the HK2 container to use a factory whenever it needs an instance of one of the resources. My factory class simply returns the Spring managed instance of the resource.
Before the factory returns the Spring-managed bean, I use the Jersey/HK2 ServiceLocator to inject things that Jersey provides. For example, anything annotated with #Context.
My javax.ws.rs.Application looks like this:
public class RestConfig extends ResourceConfig {
private static final Log log = LogFactory.getLog(RestConfig.class);
#Inject
public RestConfig(ServiceLocator locator) {
super();
// specific to my app. get your spring beans however you like
Collection<Object> beans = BeanLocator.beansByAnnotation(RestResource.class);
DynamicConfiguration c = Injections.getConfiguration(locator);
for (Object bean : beans)
{
// tell jersey to use a factory for any interface that the bean implements. since your resources don't implement interfaces,
// you'll want to do something a bit different here.
for (Class<?> currentInterface : bean.getClass().getInterfaces())
{
if (log.isTraceEnabled())
log.trace("binding " + currentInterface.getSimpleName() + " to Spring managed bean");
ServiceBindingBuilder<Object> bb = Injections.newFactoryBinder(new StaticLookupFactory(locator, bean));
bb.to(currentInterface);
Injections.addBinding(bb, c);
}
}
// commit the changes to the HK2 container (don't skip this step!)
c.commit();
property("jersey.config.disableMoxyJson.server", true);
packages("com.foo.web.rest");
register(MoxyXmlFeature.class);
}
// a "factory" where the provide() method returns the spring managed bean
// that was passed to the constructor.
private static class StaticLookupFactory implements Factory<Object> {
private ServiceLocator locator;
private Object bean;
StaticLookupFactory(ServiceLocator locator, Object bean)
{
this.locator = locator;
this.bean = bean;
}
#Override
public Object provide() {
// inject this annotated with #Context, #Inject, etc
locator.inject(bean);
return bean;
}
#Override
public void dispose(Object instance) {
}
}
}
BeanLocator is a utility class that I wrote that makes it easy to grab bean instances using static methods when autowiring isn't available. For example, when working outside of Spring managed beans. Not too much going on there:
public static Collection<Object> beansByAnnotation(Class<? extends Annotation> annotation)
{
return applicationContext.getBeansWithAnnotation(annotation).values();
}
RestResource is also specific to our app. It's a custom stereotype that works like #Component, #Service, etc:
#Target({ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
#Component
public #interface RestResource {
String value() default "";
}
Note that Jersey allows you to register custom implementations of org.glassfish.jersey.server.spring.ComponentProvider to manage the lifecycle of resources on your own. I tried it but couldn't get it to recognize my implementation no matter what I did.
One other note... the locator.inject(bean) call that activates the Jersey dependency injection mechanism will processes anything marked with #Inject. Use #Autowired within your classes or configure your beans with XML to avoid having both Spring and Jersey attempt to resolve values for things annotated with #Inject.
We have a custom, asynchronous ContextLoader, so the interim solution required placing a total hack in the Jersey-Spring3 source to wait for the application to initialize before the custom component provider initializes.
P.S. For any poor soul who finds themselves having to do something like this, make sure META-INF/settings contains the SpringComponentProvider configuration.
(2014-04-18) Elaborating for #Scott
Note that this is a terrible hack and I would only attempt such a thing as a last resort when all other attempts have failed, like in my case. Also I would consult the Jersey mailing group about your problem before attempting anything like this.
That said... this is what I did to solve my problem:
Literally copied the source code of spring-jersey3 into my application/server, modifying the header of every file with the appropriate tags as per the license;
Created the following class --
===>
/**
* Hack class for RN-8979.
*
* #author ryan
*
*/
public class ContextLoadWaiter {
private static final Logger logger = Logger.getLogger(ContextLoadWaiter.class);
public void doWait() {
try {
while (ContextLoaderHttpInterceptor.isNotStarted()) {
logger.info("Waiting for ContextLoader to start...");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
logger.error("SpringComponentProvider was interrupted!");
}
}
}
Note that this is specific to *our* code-base as ContextLoaderHttpInterceptor is an http servlet where isNotStarted returns true if our custom ContextLoader (which happens to be asynchronous) is not yet loaded.
The custom asynchronous ContextLoader was put in place sometime by somebody for some reason along the lines of allowing the UI to display a "loading" page while the server boots up. (Probably not the correct way to add this UI "feature", but the code was there and the UI depended on it, so I had to deal with it...)
Since this part will not apply directly to you, the key thing is to debug through SpringComponentProvider (from here) and look at the value of the ClassPathXmlApplicationContext. If it is null, as it is in our case, then you need to figure out why it is null and wait on whatever ContextLoader you use to load before you initialize this component.
Placed this hacky line in SpringComponentProvider --
==>
...
private final ContextLoadWaiter waiter = new ContextLoadWaiter();
...
#Override
public void initialize(ServiceLocator locator) {
waiter.doWait(); // Wait on our asynchronous context loader.
this.locator = locator;
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Context lookup started");
}
...
Created this file: META-INF/services/org.glassfish.jersey.server.spi.ComponentProvider with the contents being the fully qualified classpath to the SpringComponentProvider, e.g. com.company.server.nbi.rest.internal.jspring.SpringComponentProvider
Added the custom Jersey-spring3 package as a package to scan in the application; see below...
==>
/**
* Application configuration.
*
* #author ryan
*
*/
public class MyJerseyApplication extends ResourceConfig {
private static final class Messages {
static final String INF_STARTING_APPLICATION = "Starting %s!";
}
private static final Logger logger = Logger.getLogger(MyJerseyApplication.class);
public MyJerseyApplication() {
packages(
/* Internal providers */
"com.company.server.nbi.rest.providers",
/* Internal filters */
"com.company.server.nbi.rest.filters",
/* Spring injection support */
"com.company.server.nbi.rest.internal.jspring", // HERE!!!
/* Json providers */
"com.fasterxml.jackson.jaxrs.json",
/* Jackson exception mappers */
"com.fasterxml.jackson.jaxrs.base");
/* Resources */
register(ResourceA.class);
register(ResourceB.class);
register(ResourceC.class);
/* Miscellaneous features */
register(MultiPartFeature.class);
register(LoggingFilter.class);
logger.info(format(Messages.INF_STARTING_APPLICATION, this.getClass().getName()));
}
}
That's "it". Definitely not a solution to be proud of, but if you are in desperation mode like I was, it probably doesn't hurt to give it a shot.
This is the message that is key to understanding the issue. It indicates that Spring is failing to initialise correctly:
SEVERE: Spring context lookup failed, skipping spring component provider initialization.
(On a side note: because Spring is failing to initialise, the only JSR-330 implementation to try and resolve the #Inject is HK2 - which is why you're seeing the other issue).
Anyway, the problem is likely that your container isn't performing a scan for the annotations that make all the jersey-spring3 magic happen.
This behaviour is part of the Servlet 3.0 Specification (JSR-33, Section 1.6.2), so you should double check that your container supports this.
In the case of Tomcat - unless you're running Tomcat 7.0.29 or newer, you'll actually need to make sure that the Servlet version is specified in your web.xml.
http://tomcat.apache.org/tomcat-7.0-doc/changelog.html#Tomcat_7.0.29_(markt)
I hit this problem recently and it drove me nuts, and fixing the web.xml was easier than upgrading from Ubuntu/Precise!
Hope this helps!

Resources