Arquillian does not find classes - java

I set up a arquillian test to test my EJB and JPA layer:
#RunWith(Arquillian.class)
public class ClientTest {
#EJB
private ClientService client;
#Deployment
public static Archive<?> createDeployment() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addPackage(Client.class.getPackage())
.addPackage(ClientService.class.getPackage())
.addPackage(Client_.class.getPackage())
.addAsLibrary(new File("C:\\...\\ojdbc6.jar"))
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource("test-persistence.xml", "persistence.xml");
}
#Test
public void testCreate() {
Assert.assertNotNull("Client not null", client);
Client c = client.getClientById(1L);
assertNotNull(c);
}
}
Now, the log is telling me that the classes could not be found:
Okt 12, 2015 9:43:17 AM org.glassfish.weld.BeanDeploymentArchiveImpl handleEntry
WARNUNG: Error while trying to load Bean Class WEB-INF.classes.com.xyz.aip.common.AbstractEntity : java.lang.ClassNotFoundException: WEB-INF.classes.com.xyz.aip.common.AbstractEntity
Okt 12, 2015 9:43:17 AM org.glassfish.weld.BeanDeploymentArchiveImpl handleEntry
WARNUNG: Error while trying to load Bean Class WEB-INF.classes.com.xyz.aip.common.AbstractEntity_ : java.lang.ClassNotFoundException: WEB-INF.classes.com.xyz.aip.common.AbstractEntity_
I looked into the generated WAR-File and there is a
- META-INF
- WEB-INF
- classes
- com
- xyz
- aip
- common
- AbstractEntity.class
Any ideas?

what I would try is:
.addPackage(Client.class.getPackage().getName())

Related

Weld container doesn't inject proper object, it returns NULL

I am playing around with Weld CDI configuration. I got stuck with NULL being returned. Theoritically my configuration should make proper object instance created but I can't find reason it doesn't...
I looked up for similar questions, but most issues were related to use of new keyword while instantating the object. The other advise is to use application server. I'm running wildfly, so it's not the case as well.
Log:
Feb 17, 2021 12:12:18 AM org.jboss.weld.bootstrap.WeldStartup <clinit>
INFO: WELD-000900: 4.0.0 (Final)
Feb 17, 2021 12:12:19 AM org.jboss.weld.bootstrap.WeldStartup startContainer
INFO: WELD-000101: Transactional services not available. Injection of #Inject UserTransaction not available. Transactional observers will be invoked synchronously.
Feb 17, 2021 12:12:19 AM org.jboss.weld.environment.se.WeldContainer fireContainerInitializedEvent
INFO: WELD-ENV-002003: Weld SE container 75c04868-bd06-4acb-874c-db603ada27b0 initialized
Exception in thread "main" java.lang.NullPointerException
at MessagePrinter.printMessage(MessagePrinter.java:9)
at Main.main(Main.java:10)
Weld SE container 75c04868-bd06-4acb-874c-db603ada27b0 shut down by shutdown hook
Process finished with exit code 1
Here's my setup:
beans.xml simple as can be
<?xml version="1.0"?>
<beans bean-discovery-mode="all" version="1.1"
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"/>
Main class - creating Weld container
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
public class Main {
public static void main(String[] args) {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
MessagePrinter printer = container.select(MessagePrinter.class).get();
printer.printMessage();
weld.shutdown();
}
}
MessagePrinter class
import javax.inject.Inject;
public class MessagePrinter {
#Inject
private MessageProducer messageProducer;
public void printMessage() {
String message = messageProducer.getMessage();
System.out.println(message);
}
}
So above MessageProducer variable is always null although one only existing MessageProducer implementation (mark as #default) should be injected...
MessageProducer interface
public interface MessageProducer {
public String getMessage();
}
SimpleMessageProducer class (MessageProducer implementation)
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Default;
#Default
#Any
public class SimpleMessageProducer implements MessageProducer {
#Override
public String getMessage() {
return "Example message " + System.currentTimeMillis();
}
}
Project structure:
-src
--java
---FileMessage
---FileMessageProducer
---Main
---MessagePrinter
---MessageProducer
---SimpleMessageProducer
-resources
--META-INF
---beans.xml
As you are using Weld 4.0.0.Final, you should use jakarta.inject namespace instead of javax.inject.
You probably are having issues due overlapping classpaths. Keep only the org.jboss.weld.se:weld-se-core:4.0.0.Final dependency and you will probably be fine.

Jersey Test fails when running method from main package -> NullPointerException at target(...)

So I have tested it with this example:
Path: pkg > src > test > java > rest > SimpleJerseyTest
public class SimpleJerseyTest extends JerseyTest {
#Path("hello")
public static class HelloResource {
#GET
public String getHello() {
return "Hello World!";
}
}
#Override
protected Application configure() {
return new ResourceConfig(HelloResource.class);
}
#Test
public void test() {
Response response = target("hello").request().get();
assertEquals("Http Response should be 200: ", Response.Status.OK.getStatusCode(), response.getStatus());
assertEquals("Http Content-Type should be: ", MediaType.TEXT_HTML, response.getHeaderString(HttpHeaders.CONTENT_TYPE));
String content = response.readEntity(String.class);
System.out.println("Gotten response: " + content);
assertEquals("Content of ressponse is: ", "Hello World!", content);
}
}
This is the output of the test:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Jul 24, 2020 11:29:07 AM org.glassfish.jersey.test.grizzly.GrizzlyTestContainerFactory$GrizzlyTestContainer <init>
INFO: Creating GrizzlyTestContainer configured at the base URI http://localhost:9998/
Jul 24, 2020 11:29:08 AM org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [localhost:9998]
Jul 24, 2020 11:29:08 AM org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.
Gotten response: Hello World!
Jul 24, 2020 11:29:08 AM org.glassfish.grizzly.http.server.NetworkListener shutdownNow
INFO: Stopped listener bound to [localhost:9998]
Process finished with exit code 0
But when I put the REST service class at in the main package, it doesnt work anymore (NullPointerException):
Package: pkg > src > main > java > rest > BookService
#Path("books")
public class BookService {
#GET
public String getAll() {
return "test";
}
}
And then the Test:
Package: pkg > src > test > rest > BookServiceTest
class BookServiceTest extends JerseyTest {
#Override
protected Application configure() {
return new ResourceConfig(BookService.class);
}
#Test
void get() {
Response response = target("books").request().get();
}
}
This is the output of the test:
java.lang.NullPointerException
at org.glassfish.jersey.test.JerseyTest.target(JerseyTest.java:541)
at org.glassfish.jersey.test.JerseyTest.target(JerseyTest.java:555)
at rest.BookServiceTest.get(BookServiceTest.java:21)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
// ...
Process finished with exit code -1
What is the difference? Does anyone have a clue, why it works with a static inner class, but not with a external one?
Figured it out - I used the wrong import.
Instead of import org.junit.jupiter.api.Test it should be import org.junit.Test.

Where to set source of application.yml in Java Spring when using classpath; currently uses sub module

I have a project with some main source code (Reading Configurations and StartUp-Listener to start several services) and multiple submodules. There are resource-folders in the main project as well as in the sub modules. Currently, I have to store the application.yml in one of the submodules; the application.yml in my main source resources is ignored.
Project-Structure:
-Main
-SubModule1
-Submodule2
-main
-resources
-config
-application.yml_
-Submodule3
-MainSourceCode (including the submodules)
-main
-resources
-config
-application.yml
Remarks:
The name of the whole project used to be the name of Submodule2 (so, there might be some config leftover)
If I rename the application.yml_ in Submodule2 to application.yml, everything works
That's, how I read the configuration:
#Configuration
#Order(100)
#PropertySources({
#PropertySource(value = "file:../../../../../resources/config/application.yml", ignoreResourceNotFound = true),
#PropertySource("classpath:/config/application.yml")
})
public class AuthorizationControllerConfiguration {
...
I receive the output:
2019-08-28 08:49:58.054 INFO 19812 --- [ main] o.s.c.a.ConfigurationClassParser : Properties location [file:../../../../../resources/config/application.yml] not resolvable: ..\..\..\..\..\resources\config\application.yml (System cannot find file)
2019-08-28 08:49:58.054 WARN 19812 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [de.......AuthorizationControllerConfiguration]; nested exception is java.io.FileNotFoundException: class path resource [config/application.yml] cannot be opened because it does not exist
Config1 is ignored as expected, Config2 is - whyever - read from the SubModule2, not from the main module
So, basically my program (run from IntelliJ btw.) selects from the wrong source.
Where do I have to look at to change the source of "classpath"?
Unfortunately, the #PropertySources annotation does not work for YML files out of the box see this blog
To resolve the issue, you will need to add a custom PropertySourceFactory.
Also, from the previously mentioned blog post:
public class YamlPropertySourceFactory implements PropertySourceFactory {
#Override
public PropertySource<?> createPropertySource(#Nullable String name, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
// for ignoreResourceNotFound
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException)
throw (FileNotFoundException) e.getCause();
throw e;
}
}
}
This should address the issue.

Java rest server : make a unit test

I try to make a unit test for a standalone rest server. If I run the rest server it work nice. But I don't know how to make the UnitTest running.
My main class :
public class Main {
private static final int DEFAULT_PORT = 8080;
private final int serverPort;
private final Server restServer;
public Main(final int serverPort) throws Exception {
this.serverPort = serverPort;
restServer = configureServer();
restServer.start();
restServer.join();
}
public void close() throws Exception {
if (restServer != null) {
restServer.stop();
}
}
private Server configureServer() {
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.packages(Main.class.getPackage().getName());
resourceConfig.register(JacksonFeature.class);
ServletContainer servletContainer = new ServletContainer(resourceConfig);
ServletHolder sh = new ServletHolder(servletContainer);
Server server = new Server(serverPort);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.addServlet(sh, "/*");
server.setHandler(context);
return server;
}
public static void main(String[] args) throws Exception {
int serverPort = DEFAULT_PORT;
if (args.length >= 1) {
try {
serverPort = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
new Main(serverPort);
}
The resource class :
#Path("builder")
public class ReportBuilderResource {
#POST
#Path("/build")
#Consumes(MediaType.APPLICATION_JSON)
#Produces({MediaType.TEXT_PLAIN})
public String makeReport(final ReportDescription reportDescription) {
return reportDescription.getName();
}
}
My Unit test class :
public class ReportBuilderResourceTest extends JerseyTest {
#Override
public AppDescriptor configure() {
return new WebAppDescriptor.Builder()
.initParam(WebComponent.RESOURCE_CONFIG_CLASS, ClassNamesResourceConfig.class.getName())
.initParam(ClassNamesResourceConfig.PROPERTY_CLASSNAMES, ReportBuilderResource.class.getName())
.build();
}
#Test
public void testBuildReport() throws Exception {
System.out.println("Test Build Report");
ReportDescription reportDescription = new ReportDescription();
JSONObject jsonObject = new JSONObject(reportDescription);
resource().path("builder/").post(jsonObject.toString());
}
And the output log :
juil. 31, 2015 9:48:53 AM com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer <init>
INFO: Creating low level InMemory test container configured at the base URI http://localhost:9998/
Running com.fdilogbox.report.serveur.ReportBuilderResourceTest
juil. 31, 2015 9:48:53 AM com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer start
INFO: Starting low level InMemory test container
juil. 31, 2015 9:48:53 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.19 02/11/2015 03:25 AM'
Test Build Report
juil. 31, 2015 9:48:54 AM com.sun.jersey.api.container.filter.LoggingFilter filter
INFO: 1 * Server in-bound request
1 > POST http://localhost:9998/builder/
1 > Content-Type: text/plain
1 >
{"name":null,"report":null}
juil. 31, 2015 9:48:54 AM com.sun.jersey.api.container.filter.LoggingFilter$Adapter finish
INFO: 1 * Server out-bound response
1 < 405
1 < Allow: OPTIONS
1 <
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.497 sec <<< FAILURE! - in com.fdilogbox.report.serveur.ReportBuilderResourceTest
testBuildReport(com.fdilogbox.report.serveur.ReportBuilderResourceTest) Time elapsed: 0.496 sec <<< ERROR!
com.sun.jersey.api.client.UniformInterfaceException: Client response status: 405
at com.sun.jersey.api.client.WebResource.voidHandle(WebResource.java:709)
at com.sun.jersey.api.client.WebResource.post(WebResource.java:238)
at com.fdilogbox.report.serveur.ReportBuilderResourceTest.testBuildReport(ReportBuilderResourceTest.java:47)
I think the server is not "running" for the test. How can'I do this?
Your resource listens to "/builder", but the only method inside listens to "/builder/build". Since there is no method listening to #post and "/builder" you get a Http 405 - Method not allowed.
You can either remove #Path("/build") from the "makeReport" method, or change resource().path("builder/build")... in your test.
Btw:
You only need to add one of these contatiner adapters and this snippet to run a unit tests with Jersey 2:
public class ReportBuilderResourceTest extends JerseyTest {
#Override
protected Application configure() {
return new ResourceConfig(ReportBuilderResource.class);
}
...
}

Spring annotation #Value - What am I missing?

I've inherited some Java code. Several classes have their instance variables initialized from property values in /WEB-INF/servlet.properties like this:
#Value("${context.root}")
private String contextRoot;
When I try this in a new class, the instance variable is not initialized. My class is constructed similarly to the one that works, but it is in a different package (com.company.app.utilities vs. com.company.app.service) Both import the same class:
import org.springframework.beans.factory.annotation.Value;
Both have corresponding public getter and setter methods.
I've reviewed some Spring documentation and /WEB-INF/applicationContext.xml, but I don't see anything obvious that I need to configure.
Any assistance is greatly appreciated.
Update:
I see the following entries in the log:
[localhost-startStop-1] 03 Dec 2014 02:47:10,791 INFO : org.springframework.context.support.PropertySourcesPlaceholderConfigurer - Loading properties file from ServletContext resource [/WEB-INF/servlet.properties]
[localhost-startStop-1] 03 Dec 2014 02:47:10,938 INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#601e8f7d: defining beans [...,contactServiceImpl,s3Transfer,...]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory#32f5f812
I've omitted all other singletons from the log entry, to highlight that both the original class and my class are in the list; however, I created a constructor, whereas the original class has no constructor. The next line in the log is the exception I throw in a getter method when the value is null, caught inside the constructor:
[localhost-startStop-1] 03 Dec 2014 02:47:12,730 ERROR: com.company.app.utilities.S3Transfer - bucketName is null!
java.lang.Exception: bucketName is null!
at com.company.app.utilities.S3Transfer.getBucketName(S3Transfer.java:129)
at com.company.app.utilities.S3Transfer.<init>(S3Transfer.java:48)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1000)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:599)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:518)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:160)
...
Should I remove the constructor? If so, is there additional Spring configuration to instantiate a singleton of this class? Thanks.
Update 2014-12-03:
I think I've been away from Java too long, as the last time I coded AOP, there was no Spring Framework, and it's got me a bit confused. When you say "instantiated by Spring", does this mean to place #Autowired in the class that uses my new class? I've made this change and I've rewritten my class to implement an interface, but now Tomcat fails to restart properly. Code, properties and logs below:
package com.company.app.utilities;
import com.company.app.bean.Contact;
import java.io.InputStream;
public interface S3Transfer {
String storeContactProfilePicture(Long idUser, Contact contact);
String storeContactProfilePicture(Long idUser, Long idContact, InputStream inStream);
String storeUserProfilePicture(Long idUser, String fileName, String accountType);
}
package com.company.app.utilities;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.company.app.bean.Contact;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
public class S3TransferImpl implements S3Transfer {
private final AmazonS3 s3client = new AmazonS3Client();
private final Logger logger = Logger.getLogger(getClass());
#Value("${context.root}")
private String contextRoot;
#Value("${s3.bucket.name}")
private String bucketName;
#Value("${contact.profile.picture}")
private String contactProfilePictureKey;
#Value("${user.profile.picture}")
private String userPictureKey;
public String storeContactProfilePicture(Long idUser, Contact contact) {
String keyName = getContactProfilePictureKey().replaceAll("<<idUsr>>", idUser.toString()).replaceAll("<<idContact>>", contact.getIdContact().toString());
String fileName = contact.getPicture();
storeObjectFromFileName(fileName, keyName);
return contextRoot + keyName;
}
public String storeContactProfilePicture(Long idUser, Long idContact, InputStream inStream) {
String keyName = getContactProfilePictureKey().replaceAll("<<idUsr>>", idUser.toString()).replaceAll("<<idContact>>", idContact.toString());
storeObject(inStream, keyName);
return contextRoot + keyName;
}
public String storeUserProfilePicture(Long idUser, String fileName, String accountType) {
String keyName = getUserPictureKey().replaceAll("<<idUsr>>", idUser.toString()).replace("<<socialNetwork>>", accountType);
storeObjectFromFileName(fileName, keyName);
return contextRoot + keyName;
}
private void storeObjectFromFileName(String fileName, String keyName) {
try {
logger.info("Uploading " + fileName + " to " + keyName);
InputStream inStream = new URL(fileName).openStream();
storeObject(inStream, keyName);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
private void storeObject(InputStream inStream, String keyName) {
try {
this.s3client.putObject(new PutObjectRequest(getBucketName(), keyName, inStream, null));
} catch (AmazonServiceException ase) {
logger.error("Caught an AmazonServiceException, which "
+ "means your request made it "
+ "to Amazon S3, but was rejected with an error response"
+ " for some reason.");
logger.error("Error Message: " + ase.getMessage());
logger.error("HTTP Status Code: " + ase.getStatusCode());
logger.error("AWS Error Code: " + ase.getErrorCode());
logger.error("Error Type: " + ase.getErrorType());
logger.error("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
logger.error("Caught an AmazonClientException, which "
+ "means the client encountered "
+ "an internal error while trying to "
+ "communicate with S3, "
+ "such as not being able to access the network.");
logger.error("Error Message: " + ace.getMessage());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
public String getContextRoot() {
return contextRoot;
}
public void setContextRoot(String contextRoot) {
this.contextRoot = contextRoot;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
private String getContactProfilePictureKey() {
return contactProfilePictureKey;
}
private void setContactProfilePictureKey(String contactProfilePictureKey) {
this.contactProfilePictureKey = contactProfilePictureKey;
}
private String getUserPictureKey() {
return userPictureKey;
}
private void setUserPictureKey(String userPictureKey) {
this.userPictureKey = userPictureKey;
}
}
The classes that use S3Transfer now have the following code:
#Autowired
private S3Transfer s3Transfer;
Both /WEB-INF/applicationContext.xml and /WEB-INF/app-web-servlet.xml have the following elements within the complex bean element:
<context:annotation-config />
<context:component-scan base-package="com.company.app" />
<context:property-placeholder location="/WEB-INF/servlet.properties" />
When I restart Tomcat, initialization fails. Here are some of the relevant log entries:
[localhost-startStop-1] 03 Dec 2014 18:39:03,407 INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
[localhost-startStop-1] 03 Dec 2014 18:39:03,926 INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
[localhost-startStop-1] 03 Dec 2014 18:39:05,990 INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
[localhost-startStop-1] 03 Dec 2014 18:39:07,983 INFO : org.springframework.context.support.PropertySourcesPlaceholderConfigurer - Loading properties file from ServletContext resource [/WEB-INF/servlet.properties]
[localhost-startStop-1] 03 Dec 2014 18:39:08,708 INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#63655d7a: defining beans [... {long list, but s3TransferImpl is not in the list} ...]; root of factory hierarchy
[localhost-startStop-1] 03 Dec 2014 18:39:10,667 INFO : org.springframework.jdbc.datasource.DriverManagerDataSource - Loaded JDBC driver: com.mysql.jdbc.Driver
[localhost-startStop-1] 03 Dec 2014 18:39:20,152 ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#0' while setting bean property 'sourceList' with key [0]; nested exception is ... {long list of nested exceptions}...; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.app.utilities.S3Transfer] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
Update 2014-12-03 14:50 EST:
Apparently, both my interface and class needed an #Service annotation, as Tomcat restarted successfully. What is the purpose of this annotation?
The package of the new class i.e. com.company.app.service needs to be added to the xml file which has the spring configuration.
You need to add this to your spring XML configuration file
<beans>
<context:component-scan base-package="com.package.containing.yourclass" />
</beans>
You need to this so that Spring understands which classes it needs to scan for annotations and/or creating beans.
Could you please share the code where you are trying to access the variable. If it is inside contructor, then you will get error. As singleton beans being instiated during loading will not be able to access these values from property configurator. You may consider to move your code to in-it method, so that your variable will set while accessing the field.
Also, confirm if your class is being instantited by spring container, not by some other means like new operator

Categories

Resources