wicket,spring jpa repository - nullpointer on #Autowire - spring

Im trying to build an application based on wicket, Spring jpa repositories, and Mysql.
The problem is, my Service classes just don't want to autowire. I got a nullpointer exception if i want to use my autowired class.
In fact, i got double nullpointer: My BaseServiceConfig.java doesnt autowire the implementation, and the autowired repository in the itnerface is also null. So, the question is why.
public final class ArmyBuilderPanel extends Panel {
#Autowired
DiskService diskService; //--> frist null, before setting it.
public ArmyBuilderPanel(String id) {
super(id);
add(new Label("armyPanel", "Content placeholder: Army builder panel"));
diskService = new DiskServiceImpl();
diskService.save(new Disk()); //--> second nullpointer
} }
Im trying to do this with minimal to no xml, all the coniguration was done in java classes. Let me show you the code:
Repository interface:
#Transactional
public interface DiskRepository extends JpaRepository<Disk, Long> {
}
Service itnerface:
public interface DiskService {
public Disk save(Disk entity);
}
Service impementation:
#Service
public class DiskServiceImpl implements DiskService {
#Autowired
DiskRepository diskRepo;
#Override
public Disk save(Disk entity) {
return diskRepo.save(entity);
}
}
BaseServiceConfig.java
#Configuration
#EnableJpaRepositories(basePackages = {"hu.diskwars"})
public class BaseServiceConfig {
#Bean
DiskService diskService() {
return new DiskServiceImpl();
}
}
PersistenceJPAConfig.java
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = {"hu.diskwars"}) public class
PersistenceJPAConfig implements DisposableBean {
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[]{"hu.diskwars"});
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/whdiskwars_db");
dataSource.setUsername("Westy");
dataSource.setPassword("pass");
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
return new Properties() {
{ // Hibernate Specific:
setProperty("hibernate.hbm2ddl.auto", "create-drop");
setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
}
};
}
#Override
public void destroy() throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
} }
BaseServiceConfig.java (autowiring the implementation)
#Configuration #EnableJpaRepositories(basePackages = {"hu.diskwars"})
public class BaseServiceConfig {
#Bean
DiskService diskService() {
return new DiskServiceImpl();
}
}
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">
>
> <display-name>diskwars</display-name>
> <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>hu.diskwars.config</param-value> </context-param>
>
> <listener>
> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
> </listener>
> <filter> <filter-name>wicket.diskwars</filter-name> <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
> <init-param> <param-name>applicationClassName</param-name>
> <param-value>hu.diskwars.view.application.WicketApplication</param-value>
> </init-param> </filter>
>
> <filter-mapping> <filter-name>wicket.diskwars</filter-name>
> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>hu.dwdb</groupId>
<artifactId>diskwars</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>diskwars</name>
<description></description>
<properties>
<wicket.version>6.13.0</wicket.version>
<jetty.version>7.6.13.v20130916</jetty.version>
<wtp.version>none</wtp.version>
<slf4j.version>1.6.1</slf4j.version>
<spring.version>3.2.2.RELEASE</spring.version>
<jpa.version>1.2.0.RELEASE</jpa.version>
<hibernate.version>4.2.0.Final</hibernate.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${jpa.version}</version>
<type>jar</type>
</dependency>
<!-- WICKET DEPENDENCIES -->
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-core</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-extensions</artifactId>
<version>${wicket.version}</version>
</dependency>
<!-- LOGGING DEPENDENCIES - LOG4J -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<!-- JUNIT DEPENDENCY FOR TESTING -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- JETTY DEPENDENCIES FOR TESTING -->
<dependency>
<groupId>org.eclipse.jetty.aggregate</groupId>
<artifactId>jetty-all-server</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
<!-- HIBERNATE DEPENDENCIES -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- MYSQL DRIVER -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<filtering>false</filtering>
<directory>src/main/resources</directory>
</resource>
<resource>
<filtering>false</filtering>
<directory>src/main/java</directory>
<includes>
<include>**</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<testResources>
<testResource>
<filtering>false</filtering>
<directory>src/test/resources</directory>
</testResource>
<testResource>
<filtering>false</filtering>
<directory>src/test/java</directory>
<includes>
<include>**</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</testResource>
</testResources>
<plugins>
<plugin>
<inherited>true</inherited>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty.version}</version>
<configuration>
<connectors>
<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
<port>8080</port>
<maxIdleTime>3600000</maxIdleTime>
</connector>
<connector implementation="org.eclipse.jetty.server.ssl.SslSocketConnector">
<port>8443</port>
<maxIdleTime>3600000</maxIdleTime>
<keystore>${project.build.directory}/test-classes/keystore</keystore>
<password>wicket</password>
<keyPassword>wicket</keyPassword>
</connector>
</connectors>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<downloadSources>true</downloadSources>
<wtpversion>${wtp.version}</wtpversion>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>Apache Nexus</id>
<url>https://repository.apache.org/content/repositories/snapshots/</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
</project>
Here is a picture of my workspace:
Thanks for the help!
http://i.stack.imgur.com/P32oV.png
EDIT:
Added SpringInjector to my base wicket application
#Override
public void init() {
super.getComponentInstantiationListeners().add(new SpringComponentInjector(this));
}
And suddenly a completly new, error pops out, in conncetion with my persistance unit.
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'entityManagerFactory' defined in class
path resource [hu/diskwars/config/PersistenceJPAConfig.class]:
Invocation of init method failed; nested exception is
java.lang.IllegalStateException: Conflicting persistence unit
definitions for name 'diskwarsPU':
file:/D:/Development/projects/diskwars/target/diskwars-1.0-SNAPSHOT/WEB-INF/classes/,
file:/D:/Development/projects/diskwars/target/diskwars-1.0-SNAPSHOT/WEB-INF/classes/
The main problem is, i dont even have a persistance.xml file. I used to (with the same exact name 'diskwarsPU', but i throw it out, when i got to know, that i can do all the configurations without it.
I cleaned, builded the project again, even deleted the target folder, no use.

Wicket know really nothing about Spring #Autowired annotation. Use Wicket #SpringBean annotation and SringComponentInjector to inject a Sring bean into Wicket components.
The full example how to use #SpringBean annotation is in question How can I get a Spring bean injected in my custom Wicket model class?

Related

Could not resolve placeholder for JavaFX application with Spring Boot

I have a problem using Spring boot with JavaFX. I have the following error when starting my new application:
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.application.ui.title' in value "${spring.application.ui.title}"
I follow this tutorial: https://blog.jetbrains.com/idea/2019/11/tutorial-reactive-spring-boot-a-javafx-spring-boot-application/ to create it.
So here are my classes:
#SpringBootApplication
public class AgricultureApplication {
public static void main(String[] args) {
Application.launch(ApplicationStartUp.class,args);
}
}
public class ApplicationStartUp extends Application {
private ConfigurableApplicationContext applicationContext;
#Override
public void init() {
applicationContext = new SpringApplicationBuilder(AgricultureApplication.class).run();
}
#Override
public void stop(){
applicationContext.close();
Platform.exit();
}
#Override
public void start(Stage primaryStage){
applicationContext.publishEvent(new StageReadyEvent(primaryStage));
}
public static void main(String[] args) {
launch(args);
}
}
#Component
public class StageInitializer implements ApplicationListener<StageReadyEvent> {
private final String applicationTitle;
private ApplicationContext applicationContext;
public StageInitializer(#Value("${spring.application.ui.title}") String applicationTitle, ApplicationContext applicationContext){
super();
this.applicationTitle = applicationTitle;
this.applicationContext = applicationContext;
}
#Override
public void onApplicationEvent(StageReadyEvent stageReadyEvent) {
final Stage primaryStage = stageReadyEvent.getStage();
try {
FXMLLoader fxmlLoader = new FXMLLoader(new ClassPathResource("/main.fxml").getURL());
fxmlLoader.setControllerFactory(aClass -> applicationContext.getBean(aClass));
Parent parent = fxmlLoader.load();
Scene scene = new Scene(parent);
primaryStage.setResizable(false);
primaryStage.setScene(scene);
primaryStage.setTitle(applicationTitle);
primaryStage.show();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
public class StageReadyEvent extends ApplicationEvent {
public StageReadyEvent(Stage stage) {
super(stage);
}
public Stage getStage() {
return (Stage) this.getSource();
}
}
This is application.properties file:
spring.datasource.url=jdbc:h2:file:./AgricultureRentDb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.main.web-application-type=none
spring.application.ui.title = "Test"
spring.h2.console.enabled=true
And 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>gtech</groupId>
<artifactId>agriculturerent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.20.Final</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>29.0-jre</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>16-ea+1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Here is my project strucutre:
I think spring doesn't recognize application.properties file and i do not why, i've tried to add even the #PropertySource annotation and put absolute path to the application.properties file or to put it as classpath.
Just for notice that when i follow the tutorial i am using java 8 instead of java 11, but i do not think that's making the problem.
EDITED:
Here is my github link for the project: https://github.com/Dilyan-Galabov/Agriculture
Can you please help me to provide the problem, thank you in advance :)!
Firstly #James_D found there is a problem copying the resources files to the target folder. Actually they are not copied anyway even if i add this to my pom.xml:
<resources>
<resource>
<directory>src/main/resources</directory>
<targetPath>${project.build.outputDirectory}</targetPath>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
Even if i try to set different targetPath the problem occurs(doesn't copying the files to targetPath) and actually i think that maven does not read that code in the pom and i do not know why this is happening.

Issue with Spring ServletRegistrationBean on official example

There are the following lines in the example of Spring-ws spring guide
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
ServletRegistrationBean bean = new ServletRegistrationBean();
return new ServletRegistrationBean(servlet, "/ws/*");
I get the following error
The constructor ServletRegistrationBean(MessageDispatcherServlet, String) is undefined
How can I fix this error?. What version of Spring boot I have to use?
****EDITED
This is the pom.xml. I think it's the same than the guide. I work with Eclipse.
<?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>org.springframework</groupId>
<artifactId>gs-producing-web-service</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- tag::springws[] -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
</dependency>
<!-- end::springws[] -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- tag::xsd[] -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaDirectory>${project.basedir}/src/main/resources/</schemaDirectory>
<outputDirectory>${project.basedir}/src/main/java</outputDirectory>
<clearOutputDir>false</clearOutputDir>
</configuration>
</plugin>
<!-- end::xsd[] -->
</plugins>
</build>
</project>
Java class
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
#EnableWs
#Configuration
public class WebServiceConfig extends WsConfigurerAdapter{
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
ServletRegistrationBean bean = new ServletRegistrationBean();
return new ServletRegistrationBean(servlet, "/ws/*");
}
Do I have to add dependencies to the pom.xml. What is the dependency wher is ServletRegistrationBean(servlet, "/ws/*");
The MetricsServlet needs to implement javax.servlet.Servlet dependency. You need to have this class in your project/classpath. To do this, declare this maven dependency:
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>

Spring 5 MVC - InternalResourceViewResolver and Spring Security

I'm learning Spring, and I've got stuck on some issues i can't resolve. I run it on a GlassFish Server.
I'm implementing a simple WebMvcConfigurer which has an InternalResourceViewResolver, it looks like this:
#Configuration
#EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
#Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("messages");
return source;
}
#Override
public Validator getValidator() {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setValidationMessageSource(messageSource());
return validator;
}
}
and my Controller:
#WebServlet(value = "/")
#Controller
public class HomeController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("index.jsp").forward(request,response);
}
}
I would assume that when I run the app, it would open the index.jsp file, but it doesn't, instead I get a 404. When I change it to
request.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(request,response);
it opens it.
Also, I've followed the documentation on Spring Security and implemented simple security. From my understanding, every request should be authenticated and it should redirect the user to a login page, but it doesn't.
Here is the code:
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
public UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withUsername("user").password("user").roles("USER").build());
manager.createUser(User.withUsername("admin").password("admin").roles("USER", "ADMIN").build());
return manager;
}
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
}
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{ApplicationConfig.class, WebSecurityConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebMvcConfig.class };
}
#Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
// you might want to add stuff to enable spring security
return new Filter[]{characterEncodingFilter};
}
}
#Configuration
public class ApplicationConfig {
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
I'm suspecting that the issues are related, but can't see what I'm missing here. When i change the path in the Controller as mentioned above, I do not get redirected to the login page.
Here is the 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>org.vives</groupId>
<artifactId>spring-mvc-quickstart</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring-mvc-quickstart</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java-version>1.8</java-version>
<!-- Override Spring version -->
<spring.version>5.0.0.RELEASE</spring.version>
<jackson.version>2.9.1</jackson.version>
<thymeleaf-extras-java8time-version>3.0.1.RELEASE</thymeleaf-extras-java8time-version>
<!-- AssertJ is not a part of Spring IO platform, so the version must be provided explicitly -->
<assertj-core-version>3.8.0</assertj-core-version>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
<!-- Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<!-- Avoid issue #72 Could not initialize class org.thymeleaf.templateresolver.ServletContextTemplateResolver due to 'validation is not supported' -->
<exclusions>
<exclusion>
<artifactId>pull-parser</artifactId>
<groupId>pull-parser</groupId>
</exclusion>
</exclusions>
<version>5.2.9.Final</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-release</id>
<name>Spring Release Repository</name>
<url>https://repo.spring.io/release</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Can someone explain to me what is happening or what I'm doing wrong?
I've finally resolved the issues I had.
As for security, i forgot to add SecurityWebApplicationInitializer and as for navigation, this link helped me.

Spring Boot + Tomcat + EclipseLink causes: Cannot apply class transformer without LoadTimeWeaver specified

I'm currently struggleing around with a Spring-Boot application that should use EclipseLink as JPa implementation and that app should run within a Tomcat 8 container. Unfortunatelly I'm not able to get it to work.
As far as I read I need to add the spring-instruments.jar as java command line argument (javaagent), but I read somewhere that tomcat 8 is not requiring that because it automatically decides which load time weaver it uses. Does anyone have an idea what's going wrong here?
Basically I get the following exception when I try to run the application:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManagerFactory]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.IllegalStateException: Cannot apply class transformer without LoadTimeWeaver specified
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 95 more
Caused by: java.lang.IllegalStateException: Cannot apply class transformer without LoadTimeWeaver specified
at org.springframework.orm.jpa.persistenceunit.SpringPersistenceUnitInfo.addTransformer(SpringPersistenceUnitInfo.java:80)
at org.eclipse.persistence.jpa.PersistenceProvider.createContainerEntityManagerFactoryImpl(PersistenceProvider.java:373)
at org.eclipse.persistence.jpa.PersistenceProvider.createContainerEntityManagerFactory(PersistenceProvider.java:313)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:319)
at foo.AppConfiguration.entityManagerFactory(AppConfiguration.java:57)
at foo.AppConfiguration$$EnhancerBySpringCGLIB$$a92e9feb.CGLIB$entityManagerFactory$1(<generated>)
at foo.AppConfiguration$$EnhancerBySpringCGLIB$$a92e9feb$$FastClassBySpringCGLIB$$e4dbaad1.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
at foo.AppConfiguration$$EnhancerBySpringCGLIB$$a92e9feb.entityManagerFactory(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
My pom.xml looks like:
<?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.ss.stock</groupId>
<artifactId>SimpleTest</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://raspberrypi:8080/manager/text</url>
<server>TomcatServer</server>
<path>/StockBatch</path>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.0.RELEASE</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.10.2.RELEASE</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
</dependencies>
</project>
And my Spring boot Configuration looks like:
#Configuration
#EnableJpaRepositories("foo")
#EnableTransactionManagement
#EnableLoadTimeWeaving
#EnableScheduling
public class AppConfiguration {
#Bean
public DataSource dataSource() {
DriverManagerDataSource dmds = new DriverManagerDataSource();
dmds.setUrl("jdbc:postgresql://raspberrypi:5432/stocks");
dmds.setUsername("abc");
dmds.setPassword("***");
dmds.setDriverClassName("org.postgresql.Driver");
return dmds;
}
#Bean
public EntityManagerFactory entityManagerFactory() {
EclipseLinkJpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("foo");
factory.setDataSource(dataSource());
factory.getJpaPropertyMap().put("eclipselink.jdbc.batch-writing", "JDBC");
factory.getJpaPropertyMap().put("eclipselink.jdbc.batch-writing.size", "500");
factory.getJpaPropertyMap().put("eclipselink.persistence-context.flush-mode", "commit");
factory.afterPropertiesSet();
return factory.getObject();
}
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
}

Bean type not found when using Spring aspect and java config

I added an aspect to a working Spring+Wicket application to log thrown exceptions, and now I get the following error whenever I load the Report page:
ERROR | 2013-12-09 08:42:06,149 | qtp1559334851-16 | DefaultExceptionMapper:123 - Unexpected error occurred
org.apache.wicket.WicketRuntimeException: Can't instantiate page using constructor 'public org.jonblack.ReportPage() throws java.lang.Exception'. An exception has been thrown during construction!
at org.apache.wicket.session.DefaultPageFactory.newPage(DefaultPageFactory.java:194)
at org.apache.wicket.session.DefaultPageFactory.newPage(DefaultPageFactory.java:67)
...
Caused by: java.lang.IllegalStateException: bean of type [org.jonblack.ReportController] not found
at org.apache.wicket.spring.injection.annot.AnnotProxyFieldValueFactory.getBeanNameOfClass(AnnotProxyFieldValueFactory.java:236)
at org.apache.wicket.spring.injection.annot.AnnotProxyFieldValueFactory.getBeanName(AnnotProxyFieldValueFactory.java:179)
...
I'm using java configuration for the project, so there is no applicationContext.xml. All configuration is done via annotations, the bulk of which are in AppConfig.java.
All the code for my application is shown below. I've left out the HTML templates and HomePage as they aren't integral to the problem.
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.jonblack</groupId>
<artifactId>sw-p2</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<!-- TODO project name -->
<name>sw-p2</name>
<description></description>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<properties>
<aspectj.version>1.7.4</aspectj.version>
<spring.version>3.2.4.RELEASE</spring.version>
<wicket.version>6.11.0</wicket.version>
<jetty.version>7.6.3.v20120416</jetty.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- WICKET DEPENDENCIES -->
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-core</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-extensions</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.wicketstuff</groupId>
<artifactId>wicketstuff-annotation</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-spring</artifactId>
<version>${wicket.version}</version>
</dependency>
<!-- Spring dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</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-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- aspectj -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<!-- LOGGING DEPENDENCIES - LOG4J -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<!-- JUNIT DEPENDENCY FOR TESTING -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- JETTY DEPENDENCIES FOR TESTING -->
<dependency>
<groupId>org.eclipse.jetty.aggregate</groupId>
<artifactId>jetty-all-server</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<filtering>false</filtering>
<directory>src/main/resources</directory>
</resource>
<resource>
<filtering>false</filtering>
<directory>src/main/java</directory>
<includes>
<include>**</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<testResources>
<testResource>
<filtering>false</filtering>
<directory>src/test/resources</directory>
</testResource>
<testResource>
<filtering>false</filtering>
<directory>src/test/java</directory>
<includes>
<include>**</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</testResource>
</testResources>
<plugins>
<plugin>
<inherited>true</inherited>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty.version}</version>
<configuration>
<connectors>
<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
<port>8080</port>
<maxIdleTime>3600000</maxIdleTime>
</connector>
<connector implementation="org.eclipse.jetty.server.ssl.SslSocketConnector">
<port>8443</port>
<maxIdleTime>3600000</maxIdleTime>
<keystore>${project.build.directory}/test-classes/keystore</keystore>
<password>wicket</password>
<keyPassword>wicket</keyPassword>
</connector>
</connectors>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<downloadSources>true</downloadSources>
</configuration>
</plugin>
</plugins>
</build>
</project>
AppConfig.java
package org.jonblack;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ComponentScan;
//import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
#Configuration
#ComponentScan("org.jonblack")
#EnableAsync
#EnableAspectJAutoProxy()
public class AppConfig {
private static final Logger log = LoggerFactory.getLogger(AppConfig.class);
#Bean
public ReportController reportController() {
log.info("Getting ReportController");
return new ReportController();
}
#Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setCorePoolSize(5);
pool.setMaxPoolSize(10);
pool.setWaitForTasksToCompleteOnShutdown(true);
return pool;
}
#Bean
public ExceptionLoggingAspect exceptionLoggingAspect() {
return new ExceptionLoggingAspect();
}
#Bean
public AnnotationAwareAspectJAutoProxyCreator annotationAwareAspectJAutoProxyCreator() {
AnnotationAwareAspectJAutoProxyCreator aop = new AnnotationAwareAspectJAutoProxyCreator();
return aop;
}
}
ExceptionLoggingAspect.java
package org.jonblack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
#Aspect
#Component
public class ExceptionLoggingAspect {
private static final Logger LOG = LoggerFactory.getLogger(ExceptionLoggingAspect.class);
#AfterThrowing(pointcut="execution(* org.jonblack.ReportController.getReportData(..))", throwing="ex")
public void afterThrowing(Throwable ex) {
LOG.error(ex.getMessage());
}
}
ReportController.java
package org.jonblack;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
#Controller
public class ReportController {
private static final Logger log = LoggerFactory.getLogger(ReportController.class);
#Autowired
private ThreadPoolTaskExecutor taskExecutor;
#Async
public Future<String> getReportData() throws Exception {
log.info("Entered into getReportData()");
try {
log.info("Throwing an exception");
throw new Exception("Something went wrong");
} catch(Exception ex) {
log.error("In catch block: {}", ex.getMessage());
}
final Future<String> result = taskExecutor.submit(new Callable<String>() {
#Override
public String call() throws Exception {
return "not a fancy result";
}
});
log.info("Returning from getReportData()");
return result;
}
}
ReportPage.java
package org.jonblack;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.wicketstuff.annotation.mount.MountPath;
#MountPath("report")
public class ReportPage extends WebPage {
private static final Logger log = LoggerFactory.getLogger(ReportPage.class);
#SpringBean
ReportController reportController;
public ReportPage() throws Exception {
log.info("Starting ReportPage");
reportController.getReportData();
}
}
WicketApplication.java
package org.jonblack;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.wicketstuff.annotation.scan.AnnotatedMountScanner;
public class WicketApplication extends WebApplication
{
#Override
public Class<? extends WebPage> getHomePage()
{
return HomePage.class;
}
#Override
public void init()
{
super.init();
// Spring
getComponentInstantiationListeners().add(
new SpringComponentInjector(this));
// Annotation-driven page mounting
new AnnotatedMountScanner().scanPackage("org.jonblack").mount(this);
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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"
version="2.5">
<display-name>sw-p2</display-name>
<!-- Configuration loading -->
<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>org.jonblack.AppConfig</param-value>
</context-param>
<!-- Spring -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- Wicket -->
<filter>
<filter-name>wicket.sw-p2</filter-name>
<filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
<init-param>
<param-name>applicationClassName</param-name>
<param-value>org.jonblack.WicketApplication</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>wicket.sw-p2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
I've followed the Spring reference for Aspects but it's very thin on the ground when it comes to java configurations (and I do find the reference to be quite hard to follow).
I've also done the obligatory DuckDuckGo search and found only references to XML configurations.
On stackoverflow itself I have found this post which explains the same problem, but the cause in that instance was an incorrect annotation and incorrectly named applicationContext.xml file: neither of these helped resolve my situation. I tried using #Autowired instead of #SpringBean, and got the same NullPointerException. Given that the linked post resolved it without this change, I assume this isn't the right path to take.
The problem lies in your configuration.
#Bean
public AnnotationAwareAspectJAutoProxyCreator annotationAwareAspectJAutoProxyCreator() {
AnnotationAwareAspectJAutoProxyCreator aop = new AnnotationAwareAspectJAutoProxyCreator();
return aop;
}
This bean leads to creation of a proxy of a proxy. The #EnableAspectJAutoProxy annotation already registers an AutoProxyCreator and due to the existence of multiple, different instances, this will lead to proxy duplication.
Next to that the additional declaration of your aspect might lead to 2 aspects being instantiated.
#Bean
public ExceptionLoggingAspect exceptionLoggingAspect() {
return new ExceptionLoggingAspect();
}
Your #Aspect is also an #Component and as such will be detected by the #ComponentScan functionality.
Basically removing both beans should fix your problem.
public Future<String> getReportData() throws Exception {
log.info("Entered into getReportData()");
try {
log.info("Throwing an exception");
throw new Exception("Something went wrong");
} catch(Exception ex) { // This catch blocks swallows the exception
log.error("In catch block: {}", ex.getMessage());
}
}
Next to your configuration problems, you also have a problem with your code. Basically your aspect is useless. You have a try/catch block in your code which swallows the Exception. This swallowing leads to a situation where your aspect never sees the exception and will never trigger. From your aspects point of view the exception never happened.
Either don't catch and simply let the Exception bubble up the stack or rethrow the Exception.

Resources