Spark graphx moved to a new project due to a incompatibility of scala compiler

This commit is contained in:
Norberto Ritzmann Jr
2019-10-06 21:57:54 +02:00
parent db85c8f275
commit 45be61376e
20299 changed files with 1635696 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear
+33
View File
@@ -0,0 +1,33 @@
## Spring General Example Project
This project is used to replicate Spring Exceptions only.
### The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant articles:
- [Guide to Spring @Autowired](https://www.baeldung.com/spring-autowire)
- [Spring Profiles](https://www.baeldung.com/spring-profiles)
- [A Spring Custom Annotation for a Better DAO](https://www.baeldung.com/spring-annotation-bean-pre-processor)
- [Whats New in Spring 4.3?](https://www.baeldung.com/whats-new-in-spring-4-3)
- [Running Setup Data on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring)
- [Quick Guide to Spring Controllers](https://www.baeldung.com/spring-controllers)
- [Quick Guide to Spring Bean Scopes](https://www.baeldung.com/spring-bean-scopes)
- [Introduction To Ehcache](https://www.baeldung.com/ehcache)
- [A Guide to the Spring Task Scheduler](https://www.baeldung.com/spring-task-scheduler)
- [Guide to Spring Retry](https://www.baeldung.com/spring-retry)
- [Custom Scope in Spring](https://www.baeldung.com/spring-custom-scope)
- [A CLI with Spring Shell](https://www.baeldung.com/spring-shell-cli)
- [JasperReports with Spring](https://www.baeldung.com/spring-jasper)
- [Model, ModelMap, and ModelView in Spring MVC](https://www.baeldung.com/spring-mvc-model-model-map-model-view)
- [A Guide To Caching in Spring](https://www.baeldung.com/spring-cache-tutorial)
- [How To Do @Async in Spring](https://www.baeldung.com/spring-async)
- [@Order in Spring](https://www.baeldung.com/spring-order)
- [Spring Web Contexts](https://www.baeldung.com/spring-web-contexts)
- [Spring Cache Creating a Custom KeyGenerator](https://www.baeldung.com/spring-cache-custom-keygenerator)
- [Spring @Primary Annotation](https://www.baeldung.com/spring-primary)
- [Spring Events](https://www.baeldung.com/spring-events)
- [Spring Null-Safety Annotations](https://www.baeldung.com/spring-null-safety-annotations)
- [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class)
+254
View File
@@ -0,0 +1,254 @@
<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>
<artifactId>spring-all</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-all</name>
<packaging>war</packaging>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.shell</groupId>
<artifactId>spring-shell</artifactId>
<version>${org.springframework.shell.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>${annotation-api.version}</version>
</dependency>
<!-- aspectj -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<!-- persistence -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javassist.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
</dependency>
<!-- validation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>runtime</scope>
</dependency>
<!-- util -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>${jasperreports.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>${easymock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</dependency>
<!-- ShedLock -->
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-spring</artifactId>
<version>${shedlock.version}</version>
</dependency>
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-provider-jdbc-template</artifactId>
<version>${shedlock.version}</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>${org.springframework.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>${org.springframework.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<finalName>spring-all</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<spring.profiles.active>dev</spring.profiles.active>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<spring.profiles.active>prod</spring.profiles.active>
</properties>
</profile>
</profiles>
<properties>
<start-class>org.baeldung.sample.App</start-class>
<!-- Spring -->
<org.springframework.version>5.0.6.RELEASE</org.springframework.version>
<org.springframework.shell.version>1.2.0.RELEASE</org.springframework.shell.version>
<annotation-api.version>1.3.2</annotation-api.version>
<!-- persistence -->
<hibernate.version>5.2.5.Final</hibernate.version>
<!-- util -->
<guava.version>25.1-jre</guava.version>
<ehcache.version>3.5.2</ehcache.version>
<easymock.version>3.6</easymock.version>
<assertj.version>3.6.1</assertj.version>
<jasperreports.version>6.6.0</jasperreports.version>
<shedlock.version>2.1.0</shedlock.version>
<javassist.version>3.22.0-GA</javassist.version>
</properties>
</project>
@@ -0,0 +1,19 @@
package com.baeldung.contexts;
public class Greeting {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "Greeting [message=" + message + "]";
}
}
@@ -0,0 +1,38 @@
package com.baeldung.contexts.config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
public class AnnotationsBasedApplicationAndServletInitializer //extends AbstractDispatcherServletInitializer
{
//uncomment to run the multiple contexts example
//@Override
protected WebApplicationContext createRootApplicationContext() {
//If this is not the only class declaring a root context, we return null because it would clash
//with other classes, as there can only be a single root context.
//AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
//rootContext.register(RootApplicationConfig.class);
//return rootContext;
return null;
}
//@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext normalWebAppContext = new AnnotationConfigWebApplicationContext();
normalWebAppContext.register(NormalWebAppConfig.class);
return normalWebAppContext;
}
//@Override
protected String[] getServletMappings() {
return new String[] { "/api/*" };
}
//@Override
protected String getServletName() {
return "normal-dispatcher";
}
}
@@ -0,0 +1,17 @@
package com.baeldung.contexts.config;
import org.springframework.web.context.AbstractContextLoaderInitializer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
public class AnnotationsBasedApplicationInitializer //extends AbstractContextLoaderInitializer
{
//uncomment to run the multiple contexts example
// @Override
protected WebApplicationContext createRootApplicationContext() {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(RootApplicationConfig.class);
return rootContext;
}
}
@@ -0,0 +1,41 @@
package com.baeldung.contexts.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class ApplicationInitializer //implements WebApplicationInitializer
{
//uncomment to run the multiple contexts example
//@Override
public void onStartup(ServletContext servletContext) throws ServletException {
//Here, we can define a root context and register servlets, among other things.
//However, since we've later defined other classes to do the same and they would clash,
//we leave this commented out.
//Root XML Context
//XmlWebApplicationContext rootContext = new XmlWebApplicationContext();
//rootContext.setConfigLocations("/WEB-INF/rootApplicationContext.xml");
//Annotations Context
//AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
//rootContext.register(RootApplicationConfig.class);
//Registration
//servletContext.addListener(new ContextLoaderListener(rootContext));
//Dispatcher Servlet
//XmlWebApplicationContext normalWebAppContext = new XmlWebApplicationContext();
//normalWebAppContext.setConfigLocation("/WEB-INF/normal-webapp-servlet.xml");
//ServletRegistration.Dynamic normal = servletContext.addServlet("normal-webapp", new DispatcherServlet(normalWebAppContext));
//normal.setLoadOnStartup(1);
//normal.addMapping("/api/*");
}
}
@@ -0,0 +1,25 @@
package com.baeldung.contexts.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.baeldung.contexts.normal" })
public class NormalWebAppConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
@@ -0,0 +1,19 @@
package com.baeldung.contexts.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.baeldung.contexts.Greeting;
@Configuration
@ComponentScan(basePackages = { "com.baeldung.contexts.services" })
public class RootApplicationConfig {
@Bean
public Greeting greeting() {
Greeting greeting = new Greeting();
greeting.setMessage("Hello World !!");
return greeting;
}
}
@@ -0,0 +1,34 @@
package com.baeldung.contexts.config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
public class SecureAnnotationsBasedApplicationAndServletInitializer// extends AbstractDispatcherServletInitializer
{
//uncomment to run the multiple contexts example
//@Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
//@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext secureWebAppContext = new AnnotationConfigWebApplicationContext();
secureWebAppContext.register(SecureWebAppConfig.class);
return secureWebAppContext;
}
//@Override
protected String[] getServletMappings() {
return new String[] { "/s/api/*" };
}
//@Override
protected String getServletName() {
return "secure-dispatcher";
}
}
@@ -0,0 +1,25 @@
package com.baeldung.contexts.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.baeldung.contexts.secure" })
public class SecureWebAppConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/secure/view/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
@@ -0,0 +1,39 @@
package com.baeldung.contexts.normal;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import com.baeldung.contexts.services.GreeterService;
@Controller
public class HelloWorldController {
@Autowired
WebApplicationContext webApplicationContext;
@Autowired
private GreeterService greeterService;
private void processContext() {
WebApplicationContext rootContext = ContextLoader.getCurrentWebApplicationContext();
System.out.println("root context : " + rootContext);
System.out.println("root context Beans: " + Arrays.asList(rootContext.getBeanDefinitionNames()));
System.out.println("context : " + webApplicationContext);
System.out.println("context Beans: " + Arrays.asList(webApplicationContext.getBeanDefinitionNames()));
}
@RequestMapping(path = "/welcome")
public ModelAndView helloWorld() {
processContext();
String message = "<br><div style='text-align:center;'>" + "<h3>Normal " + greeterService.greet() + "</h3></div>";
return new ModelAndView("welcome", "message", message);
}
}
@@ -0,0 +1,49 @@
package com.baeldung.contexts.secure;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import com.baeldung.contexts.services.ApplicationContextUtilService;
import com.baeldung.contexts.services.GreeterService;
@Controller
public class HelloWorldSecureController {
@Autowired
WebApplicationContext webApplicationContext;
@Autowired
private GreeterService greeterService;
@Autowired
@Qualifier("contextAware")
private ApplicationContextUtilService contextUtilService;
private void processContext() {
ApplicationContext context = contextUtilService.getApplicationContext();
System.out.println("application context : " + context);
System.out.println("application context Beans: " + Arrays.asList(context.getBeanDefinitionNames()));
WebApplicationContext rootContext = ContextLoader.getCurrentWebApplicationContext();
System.out.println("context : " + rootContext);
System.out.println("context Beans: " + Arrays.asList(rootContext.getBeanDefinitionNames()));
System.out.println("context : " + webApplicationContext);
System.out.println("context Beans: " + Arrays.asList(webApplicationContext.getBeanDefinitionNames()));
}
@RequestMapping(path = "/welcome")
public ModelAndView helloWorld() {
processContext();
String message = "<br><div style='text-align:center;'>" + "<h3>Secure " + greeterService.greet() + "</h3></div>";
return new ModelAndView("welcome", "message", message);
}
}
@@ -0,0 +1,21 @@
package com.baeldung.contexts.services;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
@Service(value="contextAware")
public class ApplicationContextUtilService implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
}
@@ -0,0 +1,19 @@
package com.baeldung.contexts.services;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.baeldung.contexts.Greeting;
@Service
public class GreeterService {
@Resource
private Greeting greeting;
public String greet(){
return greeting.getMessage();
}
}
@@ -0,0 +1,18 @@
package com.baeldung.scheduling;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@EnableAsync
public class ScheduledFixedRateExample {
@Async
@Scheduled(fixedRate = 1000)
public void scheduleFixedRateTaskAsync() throws InterruptedException {
System.out.println("Fixed rate task async - " + System.currentTimeMillis() / 1000);
Thread.sleep(2000);
}
}
@@ -0,0 +1,12 @@
package com.baeldung.scheduling;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
@ComponentScan("com.baeldung.scheduling")
public class SpringSchedulingFixedRateConfig {
}
@@ -0,0 +1,40 @@
package org.baeldung.async;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import java.util.concurrent.Future;
@Component
public class AsyncComponent {
@Async
public void asyncMethodWithVoidReturnType() {
System.out.println("Execute method asynchronously. " + Thread.currentThread().getName());
}
@Async
public Future<String> asyncMethodWithReturnType() {
System.out.println("Execute method asynchronously " + Thread.currentThread().getName());
try {
Thread.sleep(5000);
return new AsyncResult<>("hello world !!!!");
} catch (final InterruptedException e) {
}
return null;
}
@Async("threadPoolTaskExecutor")
public void asyncMethodWithConfiguredExecutor() {
System.out.println("Execute method asynchronously with configured executor" + Thread.currentThread().getName());
}
@Async
public void asyncMethodWithExceptions() throws Exception {
throw new Exception("Throw message from asynchronous method. ");
}
}
@@ -0,0 +1,18 @@
package org.baeldung.async;
import java.lang.reflect.Method;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
@Override
public void handleUncaughtException(final Throwable throwable, final Method method, final Object... obj) {
System.out.println("Exception message - " + throwable.getMessage());
System.out.println("Method name - " + method.getName());
for (final Object param : obj) {
System.out.println("Param - " + param);
}
}
}
@@ -0,0 +1,34 @@
package org.baeldung.async.config;
import java.util.concurrent.Executor;
import org.baeldung.async.CustomAsyncExceptionHandler;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync()
@ComponentScan("org.baeldung.async")
public class SpringAsyncConfig implements AsyncConfigurer {
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
return new ThreadPoolTaskExecutor();
}
@Override
public Executor getAsyncExecutor() {
return new SimpleAsyncTaskExecutor();
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new CustomAsyncExceptionHandler();
}
}
@@ -0,0 +1,11 @@
package org.baeldung.autowire.sample;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
FooService fooService = ctx.getBean(FooService.class);
fooService.doStuff();
}
}
@@ -0,0 +1,10 @@
package org.baeldung.autowire.sample;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("org.baeldung.autowire.sample")
public class AppConfig {
}
@@ -0,0 +1,13 @@
package org.baeldung.autowire.sample;
import org.springframework.stereotype.Component;
@FormatterType("Bar")
@Component
public class BarFormatter implements Formatter {
public String format() {
return "bar";
}
}
@@ -0,0 +1,5 @@
package org.baeldung.autowire.sample;
public class FooDAO {
}
@@ -0,0 +1,13 @@
package org.baeldung.autowire.sample;
import org.springframework.stereotype.Component;
@FormatterType("Foo")
@Component
public class FooFormatter implements Formatter {
public String format() {
return "foo";
}
}
@@ -0,0 +1,17 @@
package org.baeldung.autowire.sample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class FooService {
@Autowired
@FormatterType("Foo")
private Formatter formatter;
public String doStuff() {
return formatter.format();
}
}
@@ -0,0 +1,7 @@
package org.baeldung.autowire.sample;
public interface Formatter {
String format();
}
@@ -0,0 +1,17 @@
package org.baeldung.autowire.sample;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.beans.factory.annotation.Qualifier;
@Qualifier
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface FormatterType {
String value();
}
@@ -0,0 +1,20 @@
package org.baeldung.bean.config;
import org.baeldung.bean.injection.Helm;
import org.baeldung.bean.injection.Ship;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ConstructorBasedShipConfig {
@Bean
public Ship ship() {
return new Ship(helm());
}
@Bean
public Helm helm() {
return new Helm();
}
}
@@ -0,0 +1,18 @@
package org.baeldung.bean.config;
import org.baeldung.bean.injection.Helm;
import org.baeldung.bean.injection.Ship;
import org.springframework.context.annotation.Bean;
public class SetterBasedShipConfig {
@Bean
public Ship ship() {
return new Ship();
}
@Bean
public Helm helm() {
return new Helm();
}
}
@@ -0,0 +1,14 @@
package org.baeldung.bean.injection;
public class Helm {
private String brandOfHelm = "HelmBrand";
public String getBrandOfHelm() {
return brandOfHelm;
}
public void setBrandOfHelm(String brandOfHelm) {
this.brandOfHelm = brandOfHelm;
}
}
@@ -0,0 +1,26 @@
package org.baeldung.bean.injection;
import org.springframework.beans.factory.annotation.Autowired;
public class Ship {
@Autowired
private Helm helm;
public Ship() {
helm = new Helm();
}
public Ship(Helm helm) {
this.helm = helm;
}
@Autowired
public void setHelm(Helm helm) {
this.helm = helm;
}
public Helm getHelm() {
return this.helm;
}
}
@@ -0,0 +1,30 @@
package org.baeldung.caching.config;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
@EnableCaching
@Configuration
public class ApplicationCacheConfig {
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
Cache booksCache = new ConcurrentMapCache("books");
cacheManager.setCaches(Arrays.asList(booksCache));
return cacheManager;
}
@Bean("customKeyGenerator")
public KeyGenerator keyGenerator() {
return new CustomKeyGenerator();
}
}
@@ -0,0 +1,25 @@
package org.baeldung.caching.config;
import java.util.Arrays;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
@ComponentScan("org.baeldung.caching.example")
public class CachingConfig {
@Bean
public CacheManager cacheManager() {
final SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("directory"), new ConcurrentMapCache("addresses")));
return cacheManager;
}
}
@@ -0,0 +1,14 @@
package org.baeldung.caching.config;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.util.StringUtils;
import java.lang.reflect.Method;
public class CustomKeyGenerator implements KeyGenerator {
public Object generate(Object target, Method method, Object... params) {
return target.getClass().getSimpleName() + "_" + method.getName() + "_"
+ StringUtils.arrayToDelimitedString(params, "_");
}
}
@@ -0,0 +1,18 @@
package org.baeldung.caching.eviction.controllers;
import org.baeldung.caching.eviction.service.CachingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CachingController {
@Autowired
CachingService cachingService;
@GetMapping("clearAllCaches")
public void clearAllCaches() {
cachingService.evictAllCaches();
}
}
@@ -0,0 +1,53 @@
package org.baeldung.caching.eviction.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class CachingService {
@Autowired
CacheManager cacheManager;
public void putToCache(String cacheName, String key, String value) {
cacheManager.getCache(cacheName).put(key, value);
}
public String getFromCache(String cacheName, String key) {
String value = null;
if (cacheManager.getCache(cacheName).get(key) != null) {
value = cacheManager.getCache(cacheName).get(key).get().toString();
}
return value;
}
@CacheEvict(value = "first", key = "#cacheKey")
public void evictSingleCacheValue(String cacheKey) {
}
@CacheEvict(value = "first", allEntries = true)
public void evictAllCacheValues() {
}
public void evictSingleCacheValue(String cacheName, String cacheKey) {
cacheManager.getCache(cacheName).evict(cacheKey);
}
public void evictAllCacheValues(String cacheName) {
cacheManager.getCache(cacheName).clear();
}
public void evictAllCaches() {
cacheManager.getCacheNames()
.parallelStream()
.forEach(cacheName -> cacheManager.getCache(cacheName).clear());
}
@Scheduled(fixedRate = 6000)
public void evictAllcachesAtIntervals() {
evictAllCaches();
}
}
@@ -0,0 +1,76 @@
package org.baeldung.caching.example;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
public abstract class AbstractService {
// this method configuration is equivalent to xml configuration
@Cacheable(value = "addresses", key = "#customer.name")
public String getAddress(final Customer customer) {
return customer.getAddress();
}
/**
* The method returns the customer's address,
only it doesn't find it the cache- addresses and directory.
*
* @param customer the customer
* @return the address
*/
@Cacheable({ "addresses", "directory" })
public String getAddress1(final Customer customer) {
return customer.getAddress();
}
/**
* The method returns the customer's address,
but refreshes all the entries in the cache to load new ones.
*
* @param customer the customer
* @return the address
*/
@CacheEvict(value = "addresses", allEntries = true)
public String getAddress2(final Customer customer) {
return customer.getAddress();
}
/**
* The method returns the customer's address,
but not before selectively evicting the cache as per specified paramters.
*
* @param customer the customer
* @return the address
*/
@Caching(evict = { @CacheEvict("addresses"), @CacheEvict(value = "directory", key = "#customer.name") })
public String getAddress3(final Customer customer) {
return customer.getAddress();
}
/**
* The method uses the class level cache to look up for entries.
*
* @param customer the customer
* @return the address
*/
@Cacheable
// parameter not required as we have declared it using @CacheConfig
public String getAddress4(final Customer customer) {
return customer.getAddress();
}
/**
* The method selectively caches the results that meet the predefined criteria.
*
* @param customer the customer
* @return the address
*/
@CachePut(value = "addresses", condition = "#customer.name=='Tom'")
// @CachePut(value = "addresses", unless = "#result.length>64")
public String getAddress5(final Customer customer) {
return customer.getAddress();
}
}
@@ -0,0 +1,21 @@
package org.baeldung.caching.example;
import org.baeldung.model.Book;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class BookService {
@Cacheable(value="books", keyGenerator="customKeyGenerator")
public List<Book> getBooks() {
List<Book> books = new ArrayList<Book>();
books.add(new Book(1, "The Counterfeiters", "André Gide"));
books.add(new Book(2, "Peer Gynt and Hedda Gabler", "Henrik Ibsen"));
return books;
}
}
@@ -0,0 +1,48 @@
package org.baeldung.caching.example;
public class Customer {
private int id;
private String name;
private String address;
public Customer() {
super();
}
public Customer(final String name, final String address) {
this.name = name;
this.address = address;
}
//
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(final String address) {
this.address = address;
}
public void setCustomerAddress(final String address) {
this.address = name + "," + address;
}
}
@@ -0,0 +1,79 @@
package org.baeldung.caching.example;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Component;
@Component
@CacheConfig(cacheNames = { "addresses" })
public class CustomerDataService {
// this method configuration is equivalent to xml configuration
@Cacheable(value = "addresses", key = "#customer.name")
public String getAddress(final Customer customer) {
return customer.getAddress();
}
/**
* The method returns the customer's address,
only it doesn't find it the cache- addresses and directory.
*
* @param customer the customer
* @return the address
*/
@Cacheable({ "addresses", "directory" })
public String getAddress1(final Customer customer) {
return customer.getAddress();
}
/**
* The method returns the customer's address,
but refreshes all the entries in the cache to load new ones.
*
* @param customer the customer
* @return the address
*/
@CacheEvict(value = "addresses", allEntries = true)
public String getAddress2(final Customer customer) {
return customer.getAddress();
}
/**
* The method returns the customer's address,
but not before selectively evicting the cache as per specified paramters.
*
* @param customer the customer
* @return the address
*/
@Caching(evict = { @CacheEvict("addresses"), @CacheEvict(value = "directory", key = "#customer.name") })
public String getAddress3(final Customer customer) {
return customer.getAddress();
}
/**
* The method uses the class level cache to look up for entries.
*
* @param customer the customer
* @return the address
*/
@Cacheable
// parameter not required as we have declared it using @CacheConfig
public String getAddress4(final Customer customer) {
return customer.getAddress();
}
/**
* The method selectively caches the results that meet the predefined criteria.
*
* @param customer the customer
* @return the address
*/
@CachePut(value = "addresses", condition = "#customer.name=='Tom'")
// @CachePut(value = "addresses", unless = "#result.length>64")
public String getAddress5(final Customer customer) {
return customer.getAddress();
}
}
@@ -0,0 +1,10 @@
package org.baeldung.caching.example;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Component;
@Component
@CacheConfig(cacheNames = { "addresses" })
public class CustomerServiceWithParent extends AbstractService {
//
}
@@ -0,0 +1,32 @@
package org.baeldung.controller.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class StudentControllerConfig //implements WebApplicationInitializer
{
//uncomment to run the student controller example
//@Override
public void onStartup(ServletContext sc) throws ServletException {
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.register(WebConfig.class);
root.setServletContext(sc);
sc.addListener(new ContextLoaderListener(root));
DispatcherServlet dv = new DispatcherServlet(root);
ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv);
appServlet.setLoadOnStartup(1);
appServlet.addMapping("/test/*");
}
}
@@ -0,0 +1,28 @@
package org.baeldung.controller.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "org.baeldung.controller.controller", "org.baeldung.controller.config" })
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/WEB-INF/");
bean.setSuffix(".jsp");
return bean;
}
}
@@ -0,0 +1,37 @@
package org.baeldung.controller.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* In this controller, Model, ModelMap and ModelAndView are shown as examples.
* They are all used to pass parameters to JSP pages.
* 04/09/2017
*
* @author Ahmet Cetin
*/
@Controller
public class PassParametersController {
@GetMapping("/showViewPage")
public String passParametersWithModel(Model model) {
model.addAttribute("message", "Baeldung");
return "viewPage";
}
@GetMapping("/printViewPage")
public String passParametersWithModelMap(ModelMap map) {
map.addAttribute("welcomeMessage", "welcome");
map.addAttribute("message", "Baeldung");
return "viewPage";
}
@GetMapping("/goToViewPage")
public ModelAndView passParametersWithModelAndView() {
ModelAndView modelAndView = new ModelAndView("viewPage");
modelAndView.addObject("message", "Baeldung");
return modelAndView;
}
}
@@ -0,0 +1,19 @@
package org.baeldung.controller.controller;
import org.baeldung.controller.student.Student;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RestAnnotatedController {
@GetMapping(value = "/annotated/student/{studentId}")
public Student getData(@PathVariable Integer studentId) {
Student student = new Student();
student.setName("Peter");
student.setId(studentId);
return student;
}
}
@@ -0,0 +1,21 @@
package org.baeldung.controller.controller;
import org.baeldung.controller.student.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class RestController {
@GetMapping(value = "/student/{studentId}")
public @ResponseBody Student getTestData(@PathVariable Integer studentId) {
Student student = new Student();
student.setName("Peter");
student.setId(studentId);
return student;
}
}
@@ -0,0 +1,24 @@
/**
* @author Prashant Dutta
*/
package org.baeldung.controller.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value = "/test")
public class TestController {
@GetMapping
public ModelAndView getTestData() {
ModelAndView mv = new ModelAndView();
mv.setViewName("welcome");
mv.getModel().put("data", "Welcome home man");
return mv;
}
}
@@ -0,0 +1,33 @@
package org.baeldung.controller.student;
public class Student {
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int hashCode() {
return this.id;
}
@Override
public boolean equals(Object obj) {
return this.name.equals(((Student) obj).getName());
}
}
@@ -0,0 +1,9 @@
package org.baeldung.customannotation;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("org.baeldung.customannotation")
public class CustomAnnotationConfiguration {
}
@@ -0,0 +1,14 @@
package org.baeldung.customannotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Documented
public @interface DataAccess {
Class<?> entity();
}
@@ -0,0 +1,37 @@
package org.baeldung.customannotation;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback;
@Component
public class DataAccessAnnotationProcessor implements BeanPostProcessor {
private ConfigurableListableBeanFactory configurableListableBeanFactory;
@Autowired
public DataAccessAnnotationProcessor(ConfigurableListableBeanFactory bf) {
configurableListableBeanFactory = bf;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
scanDataAccessAnnotation(bean, beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
protected void scanDataAccessAnnotation(Object bean, String beanName) {
Class<?> managedBeanClass = bean.getClass();
FieldCallback fcb = new DataAccessFieldCallback(configurableListableBeanFactory, bean);
ReflectionUtils.doWithFields(managedBeanClass, fcb);
}
}
@@ -0,0 +1,96 @@
package org.baeldung.customannotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback;
public final class DataAccessFieldCallback implements FieldCallback {
private static Logger logger = LoggerFactory.getLogger(DataAccessFieldCallback.class);
private static int AUTOWIRE_MODE = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
private static String ERROR_ENTITY_VALUE_NOT_SAME = "@DataAccess(entity) " + "value should have same type with injected generic type.";
private static String WARN_NON_GENERIC_VALUE = "@DataAccess annotation assigned " + "to raw (non-generic) declaration. This will make your code less type-safe.";
private static String ERROR_CREATE_INSTANCE = "Cannot create instance of " + "type '{}' or instance creation is failed because: {}";
private ConfigurableListableBeanFactory configurableListableBeanFactory;
private Object bean;
public DataAccessFieldCallback(final ConfigurableListableBeanFactory bf, final Object bean) {
configurableListableBeanFactory = bf;
this.bean = bean;
}
@Override
public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException {
if (!field.isAnnotationPresent(DataAccess.class)) {
return;
}
ReflectionUtils.makeAccessible(field);
final Type fieldGenericType = field.getGenericType();
// In this example, get actual "GenericDAO' type.
final Class<?> generic = field.getType();
final Class<?> classValue = field.getDeclaredAnnotation(DataAccess.class).entity();
if (genericTypeIsValid(classValue, fieldGenericType)) {
final String beanName = classValue.getSimpleName() + generic.getSimpleName();
final Object beanInstance = getBeanInstance(beanName, generic, classValue);
field.set(bean, beanInstance);
} else {
throw new IllegalArgumentException(ERROR_ENTITY_VALUE_NOT_SAME);
}
}
/**
* For example, if user write:
* <pre>
* &#064;DataAccess(entity=Person.class)
* private GenericDAO&lt;Account&gt; personGenericDAO;
* </pre>
* then this is should be failed.
*/
public boolean genericTypeIsValid(final Class<?> clazz, final Type field) {
if (field instanceof ParameterizedType) {
final ParameterizedType parameterizedType = (ParameterizedType) field;
final Type type = parameterizedType.getActualTypeArguments()[0];
return type.equals(clazz);
} else {
logger.warn(WARN_NON_GENERIC_VALUE);
return true;
}
}
public final Object getBeanInstance(final String beanName, final Class<?> genericClass, final Class<?> paramClass) {
Object daoInstance = null;
if (!configurableListableBeanFactory.containsBean(beanName)) {
logger.info("Creating new DataAccess bean named '{}'.", beanName);
Object toRegister = null;
try {
final Constructor<?> ctr = genericClass.getConstructor(Class.class);
toRegister = ctr.newInstance(paramClass);
} catch (final Exception e) {
logger.error(ERROR_CREATE_INSTANCE, genericClass.getTypeName(), e);
throw new RuntimeException(e);
}
daoInstance = configurableListableBeanFactory.initializeBean(toRegister, beanName);
configurableListableBeanFactory.autowireBeanProperties(daoInstance, AUTOWIRE_MODE, true);
configurableListableBeanFactory.registerSingleton(beanName, daoInstance);
logger.info("Bean named '{}' created successfully.", beanName);
} else {
daoInstance = configurableListableBeanFactory.getBean(beanName);
logger.info("Bean named '{}' already exist used as current bean reference.", beanName);
}
return daoInstance;
}
}
@@ -0,0 +1,30 @@
package org.baeldung.customannotation;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
public class GenericDAO<E> {
private Class<E> entityClass;
private String message;
public GenericDAO(Class<E> entityClass) {
this.entityClass = entityClass;
}
public List<E> findAll() {
message = "Would create findAll query from " + entityClass.getSimpleName();
return Collections.emptyList();
}
public Optional<E> persist(E toPersist) {
message = "Would create persist query from " + toPersist.getClass().getSimpleName();
return Optional.empty();
}
/** Only used for unit-testing. */
public final String getMessage() {
return message;
}
}
@@ -0,0 +1,14 @@
package org.baeldung.customscope;
public class TenantBean {
private final String name;
public TenantBean(String name) {
this.name = name;
}
public void sayHello() {
System.out.println(String.format("Hello from %s of type %s", this.name, this.getClass().getName()));
}
}
@@ -0,0 +1,13 @@
package org.baeldung.customscope;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
public class TenantBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
factory.registerScope("tenant", new TenantScope());
}
}
@@ -0,0 +1,21 @@
package org.baeldung.customscope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class TenantBeansConfig {
@Scope(scopeName = "tenant")
@Bean
public TenantBean foo() {
return new TenantBean("foo");
}
@Scope(scopeName = "tenant")
@Bean
public TenantBean bar() {
return new TenantBean("bar");
}
}
@@ -0,0 +1,43 @@
package org.baeldung.customscope;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
public class TenantScope implements Scope {
private Map<String, Object> scopedObjects = Collections.synchronizedMap(new HashMap<String, Object>());
private Map<String, Runnable> destructionCallbacks = Collections.synchronizedMap(new HashMap<String, Runnable>());
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
if (!scopedObjects.containsKey(name)) {
scopedObjects.put(name, objectFactory.getObject());
}
return scopedObjects.get(name);
}
@Override
public Object remove(String name) {
destructionCallbacks.remove(name);
return scopedObjects.remove(name);
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {
destructionCallbacks.put(name, callback);
}
@Override
public Object resolveContextualObject(String key) {
return null;
}
@Override
public String getConversationId() {
return "tenant";
}
}
@@ -0,0 +1,14 @@
package org.baeldung.customscope;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TenantScopeConfig {
@Bean
public static BeanFactoryPostProcessor beanFactoryPostProcessor() {
return new TenantBeanFactoryPostProcessor();
}
}
@@ -0,0 +1,24 @@
package org.baeldung.ehcache.calculator;
import org.baeldung.ehcache.config.CacheHelper;
public class SquaredCalculator {
private CacheHelper cache;
public int getSquareValueOfNumber(int input) {
if (cache.getSquareNumberCache().containsKey(input)) {
return cache.getSquareNumberCache().get(input);
}
System.out.println("Calculating square value of " + input + " and caching result.");
int squaredValue = (int) Math.pow(input, 2);
cache.getSquareNumberCache().put(input, squaredValue);
return squaredValue;
}
public void setCache(CacheHelper cache) {
this.cache = cache;
}
}
@@ -0,0 +1,29 @@
package org.baeldung.ehcache.config;
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
public class CacheHelper {
private CacheManager cacheManager;
private Cache<Integer, Integer> squareNumberCache;
public CacheHelper() {
cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build();
cacheManager.init();
squareNumberCache = cacheManager.createCache("squaredNumber", CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, Integer.class, ResourcePoolsBuilder.heap(10)));
}
public Cache<Integer, Integer> getSquareNumberCache() {
return squareNumberCache;
}
public Cache<Integer, Integer> getSquareNumberCacheFromCacheManager() {
return cacheManager.getCache("squaredNumber", Integer.class, Integer.class);
}
}
@@ -0,0 +1,39 @@
package org.baeldung.jasperreports;
import java.util.HashMap;
import java.util.Map;
import org.baeldung.jasperreports.config.JasperRerportsSimpleConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(JasperRerportsSimpleConfig.class);
ctx.refresh();
SimpleReportFiller simpleReportFiller = ctx.getBean(SimpleReportFiller.class);
simpleReportFiller.setReportFileName("employeeEmailReport.jrxml");
simpleReportFiller.compileReport();
simpleReportFiller.setReportFileName("employeeReport.jrxml");
simpleReportFiller.compileReport();
Map<String, Object> parameters = new HashMap<>();
parameters.put("title", "Employee Report Example");
parameters.put("minSalary", 15000.0);
parameters.put("condition", " LAST_NAME ='Smith' ORDER BY FIRST_NAME");
simpleReportFiller.setParameters(parameters);
simpleReportFiller.fillReport();
SimpleReportExporter simpleExporter = ctx.getBean(SimpleReportExporter.class);
simpleExporter.setJasperPrint(simpleReportFiller.getJasperPrint());
simpleExporter.exportToPdf("employeeReport.pdf", "baeldung");
simpleExporter.exportToXlsx("employeeReport.xlsx", "Employee Data");
simpleExporter.exportToCsv("employeeReport.csv");
simpleExporter.exportToHtml("employeeReport.html");
}
}
@@ -0,0 +1,109 @@
package org.baeldung.jasperreports;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.HtmlExporter;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleHtmlExporterOutput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimplePdfExporterConfiguration;
import net.sf.jasperreports.export.SimplePdfReportConfiguration;
import net.sf.jasperreports.export.SimpleWriterExporterOutput;
import net.sf.jasperreports.export.SimpleXlsxReportConfiguration;
import org.springframework.stereotype.Component;
@Component
public class SimpleReportExporter {
private JasperPrint jasperPrint;
public SimpleReportExporter() {
}
public SimpleReportExporter(JasperPrint jasperPrint) {
this.jasperPrint = jasperPrint;
}
public JasperPrint getJasperPrint() {
return jasperPrint;
}
public void setJasperPrint(JasperPrint jasperPrint) {
this.jasperPrint = jasperPrint;
}
public void exportToPdf(String fileName, String author) {
// print report to file
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(fileName));
SimplePdfReportConfiguration reportConfig = new SimplePdfReportConfiguration();
reportConfig.setSizePageToContent(true);
reportConfig.setForceLineBreakPolicy(false);
SimplePdfExporterConfiguration exportConfig = new SimplePdfExporterConfiguration();
exportConfig.setMetadataAuthor(author);
exportConfig.setEncrypted(true);
exportConfig.setAllowedPermissionsHint("PRINTING");
exporter.setConfiguration(reportConfig);
exporter.setConfiguration(exportConfig);
try {
exporter.exportReport();
} catch (JRException ex) {
Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void exportToXlsx(String fileName, String sheetName) {
JRXlsxExporter exporter = new JRXlsxExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(fileName));
SimpleXlsxReportConfiguration reportConfig = new SimpleXlsxReportConfiguration();
reportConfig.setSheetNames(new String[] { sheetName });
exporter.setConfiguration(reportConfig);
try {
exporter.exportReport();
} catch (JRException ex) {
Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void exportToCsv(String fileName) {
JRCsvExporter exporter = new JRCsvExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleWriterExporterOutput(fileName));
try {
exporter.exportReport();
} catch (JRException ex) {
Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void exportToHtml(String fileName) {
HtmlExporter exporter = new HtmlExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleHtmlExporterOutput(fileName));
try {
exporter.exportReport();
} catch (JRException ex) {
Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@@ -0,0 +1,88 @@
package org.baeldung.jasperreports;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRSaver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class SimpleReportFiller {
private String reportFileName;
private JasperReport jasperReport;
private JasperPrint jasperPrint;
@Autowired
private DataSource dataSource;
private Map<String, Object> parameters;
public SimpleReportFiller() {
parameters = new HashMap<>();
}
public void prepareReport() {
compileReport();
fillReport();
}
public void compileReport() {
try {
InputStream reportStream = getClass().getResourceAsStream("/".concat(reportFileName));
jasperReport = JasperCompileManager.compileReport(reportStream);
JRSaver.saveObject(jasperReport, reportFileName.replace(".jrxml", ".jasper"));
} catch (JRException ex) {
Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void fillReport() {
try {
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource.getConnection());
} catch (JRException | SQLException ex) {
Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex);
}
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Map<String, Object> getParameters() {
return parameters;
}
public void setParameters(Map<String, Object> parameters) {
this.parameters = parameters;
}
public String getReportFileName() {
return reportFileName;
}
public void setReportFileName(String reportFileName) {
this.reportFileName = reportFileName;
}
public JasperPrint getJasperPrint() {
return jasperPrint;
}
}
@@ -0,0 +1,29 @@
package org.baeldung.jasperreports.config;
import javax.sql.DataSource;
import org.baeldung.jasperreports.SimpleReportExporter;
import org.baeldung.jasperreports.SimpleReportFiller;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
@Configuration
public class JasperRerportsSimpleConfig {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).addScript("classpath:employee-schema.sql").build();
}
@Bean
public SimpleReportFiller reportFiller() {
return new SimpleReportFiller();
}
@Bean
public SimpleReportExporter reportExporter() {
return new SimpleReportExporter();
}
}
@@ -0,0 +1,41 @@
package org.baeldung.model;
public class Book {
private int id;
private String author;
private String title;
public Book() {
}
public Book(int id, String author, String title) {
this.id = id;
this.author = author;
this.title = title;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
@@ -0,0 +1,33 @@
package org.baeldung.nullibility;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
public class Person {
@NonNull
private String fullName;
@Nullable
private String nickName;
void setFullName(String fullName) {
if (fullName != null && fullName.isEmpty()) {
fullName = null;
}
this.fullName = fullName;
}
void setNickName(String nickName) {
if (nickName != null && nickName.isEmpty()) {
nickName = null;
}
this.nickName = nickName;
}
String getFullName() {
return fullName;
}
String getNickName() {
return nickName;
}
}
@@ -0,0 +1,6 @@
@NonNullApi
@NonNullFields
package org.baeldung.nullibility;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
@@ -0,0 +1,15 @@
package org.baeldung.order;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(Ordered.LOWEST_PRECEDENCE)
public class Average implements Rating {
@Override
public int getRating() {
return 3;
}
}
@@ -0,0 +1,14 @@
package org.baeldung.order;
import org.springframework.stereotype.Component;
import org.springframework.core.annotation.Order;
@Component
@Order(1)
public class Excellent implements Rating {
@Override
public int getRating() {
return 1;
}
}
@@ -0,0 +1,14 @@
package org.baeldung.order;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(2)
public class Good implements Rating {
@Override
public int getRating() {
return 2;
}
}
@@ -0,0 +1,6 @@
package org.baeldung.order;
public interface Rating {
int getRating();
}
@@ -0,0 +1,26 @@
package org.baeldung.persistence;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class Setup implements ApplicationListener<ContextRefreshedEvent> {
private boolean setupDone;
public Setup() {
super();
}
//
@Override
public final void onApplicationEvent(final ContextRefreshedEvent event) {
if (!setupDone) {
System.out.println();
setupDone = true;
}
}
}
@@ -0,0 +1,22 @@
package org.baeldung.primary;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
@ComponentScan(basePackages="org.baeldung.primary")
public class Config {
@Bean
public Employee johnEmployee(){
return new Employee("John");
}
@Bean
@Primary
public Employee tonyEmployee(){
return new Employee("Tony");
}
}
@@ -0,0 +1,11 @@
package org.baeldung.primary;
import org.springframework.stereotype.Component;
@Component
public class DepartmentManager implements Manager {
@Override
public String getManagerName() {
return "Department manager";
}
}
@@ -0,0 +1,20 @@
package org.baeldung.primary;
/**
* Created by Gebruiker on 7/17/2018.
*/
public class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
'}';
}
}
@@ -0,0 +1,14 @@
package org.baeldung.primary;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
@Component
@Primary
public class GeneralManager implements Manager {
@Override
public String getManagerName() {
return "General manager";
}
}
@@ -0,0 +1,8 @@
package org.baeldung.primary;
/**
* Created by Gebruiker on 7/19/2018.
*/
public interface Manager {
String getManagerName();
}
@@ -0,0 +1,17 @@
package org.baeldung.primary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by Gebruiker on 7/19/2018.
*/@Service
public class ManagerService {
@Autowired
private Manager manager;
public Manager getManager() {
return manager;
}
}
@@ -0,0 +1,20 @@
package org.baeldung.primary;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class PrimaryApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context
= new AnnotationConfigApplicationContext(Config.class);
Employee employee = context.getBean(Employee.class);
System.out.println(employee);
ManagerService service = context.getBean(ManagerService.class);
Manager manager = service.getManager();
System.out.println(manager.getManagerName());
}
}
@@ -0,0 +1,5 @@
package org.baeldung.profiles;
public interface DatasourceConfig {
void setup();
}
@@ -0,0 +1,15 @@
package org.baeldung.profiles;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("dev")
public class DevDatasourceConfig implements DatasourceConfig {
@Override
public void setup() {
System.out.println("Setting up datasource for DEV environment. ");
}
}
@@ -0,0 +1,15 @@
package org.baeldung.profiles;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("production")
public class ProductionDatasourceConfig implements DatasourceConfig {
@Override
public void setup() {
System.out.println("Setting up datasource for PRODUCTION environment. ");
}
}
@@ -0,0 +1,18 @@
package org.baeldung.profiles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class ProfileManager {
@Autowired
private Environment environment;
public void getActiveProfiles() {
for (final String profileName : environment.getActiveProfiles()) {
System.out.println("Currently active profile - " + profileName);
}
}
}
@@ -0,0 +1,12 @@
package org.baeldung.profiles;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@ComponentScan("org.baeldung.profiles")
@PropertySource(value = "classpath:application.properties")
public class SpringProfilesConfig {
}
@@ -0,0 +1,5 @@
package org.baeldung.sample;
public class Bar {
}
@@ -0,0 +1,5 @@
package org.baeldung.sample;
public class Foo {
}
@@ -0,0 +1,28 @@
package org.baeldung.sampleabstract;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
public abstract class BallService {
private RuleRepository ruleRepository;
private LogRepository logRepository;
public BallService(RuleRepository ruleRepository) {
this.ruleRepository = ruleRepository;
}
@Autowired
public final void setLogRepository(LogRepository logRepository) {
this.logRepository = logRepository;
}
@PostConstruct
public void afterInitialize() {
System.out.println(ruleRepository.toString());
System.out.println(logRepository.toString());
}
}
@@ -0,0 +1,13 @@
package org.baeldung.sampleabstract;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BasketballService extends BallService {
@Autowired
public BasketballService(RuleRepository ruleRepository) {
super(ruleRepository);
}
}
@@ -0,0 +1,18 @@
package org.baeldung.sampleabstract;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "org.baeldung.sampleabstract")
public class DemoApp {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(DemoApp.class);
}
}
@@ -0,0 +1,12 @@
package org.baeldung.sampleabstract;
import org.springframework.stereotype.Component;
@Component
public class LogRepository {
@Override
public String toString() {
return "logRepository";
}
}
@@ -0,0 +1,12 @@
package org.baeldung.sampleabstract;
import org.springframework.stereotype.Component;
@Component
public class RuleRepository {
@Override
public String toString() {
return "ruleRepository";
}
}
@@ -0,0 +1,52 @@
package org.baeldung.scheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component("scheduledAnnotationExample")
public class ScheduledAnnotationExample {
@Scheduled(fixedDelay = 1000)
public void scheduleFixedDelayTask() {
System.out.println("Fixed delay task - " + System.currentTimeMillis() / 1000);
}
@Scheduled(fixedDelayString = "${fixedDelay.in.milliseconds}")
public void scheduleFixedDelayTaskUsingExpression() {
System.out.println("Fixed delay task - " + System.currentTimeMillis() / 1000);
}
@Scheduled(fixedDelay = 1000, initialDelay = 2000)
public void scheduleFixedDelayWithInitialDelayTask() {
System.out.println("Fixed delay task with one second initial delay - " + System.currentTimeMillis() / 1000);
}
@Scheduled(fixedRate = 1000)
public void scheduleFixedRateTask() {
System.out.println("Fixed rate task - " + System.currentTimeMillis() / 1000);
}
@Scheduled(fixedRateString = "${fixedRate.in.milliseconds}")
public void scheduleFixedRateTaskUsingExpression() {
System.out.println("Fixed rate task - " + System.currentTimeMillis() / 1000);
}
@Scheduled(fixedDelay = 1000, initialDelay = 100)
public void scheduleFixedRateWithInitialDelayTask() {
System.out.println("Fixed delay task with one second initial delay - " + System.currentTimeMillis() / 1000);
}
/**
* Scheduled task is executed at 10:15 AM on the 15th day of every month
*/
@Scheduled(cron = "0 15 10 15 * ?")
public void scheduleTaskUsingCronExpression() {
System.out.println("schedule tasks using cron expressions - " + System.currentTimeMillis() / 1000);
}
@Scheduled(cron = "${cron.expression}")
public void scheduleTaskUsingExternalizedCronExpression() {
System.out.println("schedule tasks using externalized cron expressions - " + System.currentTimeMillis() / 1000);
}
}
@@ -0,0 +1,16 @@
package org.baeldung.scheduling;
public class SchedulingWithXmlConfig {
public void scheduleFixedDelayTask() {
System.out.println("Fixed delay task - " + System.currentTimeMillis() / 1000);
}
public void scheduleFixedRateTask() {
System.out.println("Fixed rate task - " + System.currentTimeMillis() / 1000);
}
public void scheduleTaskUsingCronExpression() {
System.out.println("schedule tasks using cron expressions - " + System.currentTimeMillis() / 1000);
}
}
@@ -0,0 +1,20 @@
package org.baeldung.scheduling;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
@ComponentScan("org.baeldung.scheduling")
@PropertySource("classpath:springScheduled.properties")
public class SpringSchedulingConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
@@ -0,0 +1,15 @@
package org.baeldung.scopes;
public class HelloMessageGenerator {
private String message;
public String getMessage() {
return message;
}
public void setMessage(final String message) {
this.message = message;
}
}
@@ -0,0 +1,27 @@
package org.baeldung.scopes;
public class Person {
private String name;
private int age;
public Person() {
}
public Person(final String name, final int age) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [name=" + name + "]";
}
}
@@ -0,0 +1,61 @@
package org.baeldung.scopes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
@Configuration
@ComponentScan("org.baeldung.scopes")
@EnableWebMvc
public class ScopesConfig {
@Bean
public UrlBasedViewResolver setupViewResolver() {
final UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator requestScopedBean() {
return new HelloMessageGenerator();
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator sessionScopedBean() {
return new HelloMessageGenerator();
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_APPLICATION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator applicationScopedBean() {
return new HelloMessageGenerator();
}
@Bean
@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator websocketScopedBean() {
return new HelloMessageGenerator();
}
@Bean
@Scope("prototype")
public Person personPrototype() {
return new Person();
}
@Bean
@Scope("singleton")
public Person personSingleton() {
return new Person();
}
}
@@ -0,0 +1,48 @@
package org.baeldung.scopes;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ScopesController {
public static final Logger LOG = LoggerFactory.getLogger(ScopesController.class);
@Resource(name = "requestScopedBean")
HelloMessageGenerator requestScopedBean;
@Resource(name = "sessionScopedBean")
HelloMessageGenerator sessionScopedBean;
@Resource(name = "applicationScopedBean")
HelloMessageGenerator applicationScopedBean;
@RequestMapping("/scopes/request")
public String getRequestScopeMessage(final Model model) {
model.addAttribute("previousMessage", requestScopedBean.getMessage());
requestScopedBean.setMessage("Request Scope Message!");
model.addAttribute("currentMessage", requestScopedBean.getMessage());
return "scopesExample";
}
@RequestMapping("/scopes/session")
public String getSessionScopeMessage(final Model model) {
model.addAttribute("previousMessage", sessionScopedBean.getMessage());
sessionScopedBean.setMessage("Session Scope Message!");
model.addAttribute("currentMessage", sessionScopedBean.getMessage());
return "scopesExample";
}
@RequestMapping("/scopes/application")
public String getApplicationScopeMessage(final Model model) {
model.addAttribute("previousMessage", applicationScopedBean.getMessage());
applicationScopedBean.setMessage("Application Scope Message!");
model.addAttribute("currentMessage", applicationScopedBean.getMessage());
return "scopesExample";
}
}
@@ -0,0 +1,10 @@
package org.baeldung.shell;
import java.io.IOException;
import org.springframework.shell.Bootstrap;
public class Main {
public static void main(String[] args) throws IOException {
Bootstrap.main(args);
}
}

Some files were not shown because too many files have changed in this diff Show More