This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 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
+18
View File
@@ -0,0 +1,18 @@
## Spring Core
This module contains articles about core Spring functionality
## Relevant Articles:
- [Guide to Spring @Autowired](http://www.baeldung.com/spring-autowire)
- [Spring Profiles](http://www.baeldung.com/spring-profiles)
- [A Spring Custom Annotation for a Better DAO](http://www.baeldung.com/spring-annotation-bean-pre-processor)
- [Running Setup Data on Startup in Spring](http://www.baeldung.com/running-setup-logic-on-startup-in-spring)
- [Quick Guide to Spring Bean Scopes](http://www.baeldung.com/spring-bean-scopes)
- [Custom Scope in Spring](http://www.baeldung.com/spring-custom-scope)
- [@Order in Spring](http://www.baeldung.com/spring-order)
- [Spring @Primary Annotation](http://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)
- More articles: [[<-- prev]](/spring-core)
+217
View File
@@ -0,0 +1,217 @@
<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-core-2</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-core-2</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</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>
<!-- 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>
<!-- 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-core-2</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>
<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>
<easymock.version>3.6</easymock.version>
<assertj.version>3.6.1</assertj.version>
<shedlock.version>2.1.0</shedlock.version>
<javassist.version>3.22.0-GA</javassist.version>
</properties>
</project>
@@ -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,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,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,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,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,33 @@
package org.baeldung.spring.config;
import java.util.concurrent.ExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public final class CleanupBean implements DisposableBean {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private ExecutorService setupExecutor;
public CleanupBean() {
super();
}
//
@Override
public void destroy() {
logger.info("Starting shutdown process - cleanup");
setupExecutor.shutdownNow();
logger.info("Finishing shutdown process - cleanup");
}
}
@@ -0,0 +1,32 @@
package org.baeldung.spring.config;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@ComponentScan("org.baeldung.core")
public class CoreConfig implements WebMvcConfigurer {
public CoreConfig() {
super();
}
// beans
@Bean
public ExecutorService setupExecutor() {
final int coreThreads = 4;
final int maxThreads = 8;
final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(coreThreads, maxThreads, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
threadPoolExecutor.allowCoreThreadTimeOut(true);
return threadPoolExecutor;
}
}
@@ -0,0 +1,44 @@
package org.baeldung.spring.config;
import java.util.Set;
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 MainWebAppInitializer implements WebApplicationInitializer
{
/**
* Register and configure all Servlet container components necessary to power the web application.
*/
@Override
public void onStartup(final ServletContext sc) throws ServletException {
System.out.println("MainWebAppInitializer.onStartup()");
// Create the 'root' Spring application context
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.scan("org.baeldung.spring.config");
// root.getEnvironment().setDefaultProfiles("embedded");
sc.addListener(new ContextLoaderListener(root));
DispatcherServlet dv = new DispatcherServlet(root);
final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc",dv);
appServlet.setLoadOnStartup(1);
final Set<String> mappingConflicts = appServlet.addMapping("/");
if (!mappingConflicts.isEmpty()) {
throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
}
}
}
@@ -0,0 +1,37 @@
package org.baeldung.spring.config;
import org.springframework.context.annotation.Bean;
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.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@Configuration
public class MvcConfig implements WebMvcConfigurer {
public MvcConfig() {
super();
}
// API
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/sample.html");
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
}
@@ -0,0 +1,75 @@
package org.baeldung.spring.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.google.common.base.Preconditions;
// @Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-mysql.properties" })
@ComponentScan({ "org.baeldung.persistence" })
public class PersistenceConfig {
@Autowired
private Environment env;
public PersistenceConfig() {
super();
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
sessionFactory.setPackagesToScan(new String[] { "org.baeldung.spring.persistence.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource restDataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public HibernateTransactionManager transactionManager() {
final HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory().getObject());
return txManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
return hibernateProperties;
}
}
@@ -0,0 +1,21 @@
package org.baeldung.springevents.asynchronous;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
@Configuration
@ComponentScan("org.baeldung.springevents.synchronous")
public class AsynchronousSpringEventsConfig {
@Bean(name = "applicationEventMulticaster")
public ApplicationEventMulticaster simpleApplicationEventMulticaster() {
final SimpleApplicationEventMulticaster simpleApplicationEventMulticaster = new SimpleApplicationEventMulticaster();
simpleApplicationEventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor());
return simpleApplicationEventMulticaster;
}
}
@@ -0,0 +1,46 @@
package org.baeldung.springevents.synchronous;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;
@Component
public class AnnotationDrivenEventListener {
// for tests
private boolean hitContextStartedHandler = false;
private boolean hitSuccessfulEventHandler = false;
private boolean hitCustomEventHandler = false;
@EventListener
public void handleContextStart(final ContextStartedEvent cse) {
System.out.println("Handling context started event.");
hitContextStartedHandler = true;
}
@EventListener(condition = "#event.success")
public void handleSuccessful(final GenericSpringEvent<String> event) {
System.out.println("Handling generic event (conditional): " + event.getWhat());
hitSuccessfulEventHandler = true;
}
@TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
public void handleCustom(final CustomSpringEvent event) {
System.out.println("Handling event inside a transaction BEFORE COMMIT.");
hitCustomEventHandler = true;
}
boolean isHitContextStartedHandler() {
return hitContextStartedHandler;
}
boolean isHitSuccessfulEventHandler() {
return hitSuccessfulEventHandler;
}
boolean isHitCustomEventHandler() {
return hitCustomEventHandler;
}
}
@@ -0,0 +1,22 @@
package org.baeldung.springevents.synchronous;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class ContextRefreshedListener implements ApplicationListener<ContextRefreshedEvent> {
// for tests
private boolean hitContextRefreshedHandler = false;
@Override
public void onApplicationEvent(final ContextRefreshedEvent cse) {
System.out.println("Handling context re-freshed event. ");
hitContextRefreshedHandler = true;
}
boolean isHitContextRefreshedHandler() {
return hitContextRefreshedHandler;
}
}
@@ -0,0 +1,19 @@
package org.baeldung.springevents.synchronous;
import org.springframework.context.ApplicationEvent;
public class CustomSpringEvent extends ApplicationEvent {
private static final long serialVersionUID = -8053143381029977953L;
private String message;
public CustomSpringEvent(final Object source, final String message) {
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
}
@@ -0,0 +1,14 @@
package org.baeldung.springevents.synchronous;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> {
@Override
public void onApplicationEvent(final CustomSpringEvent event) {
System.out.println("Received spring custom event - " + event.getMessage());
}
}
@@ -0,0 +1,31 @@
package org.baeldung.springevents.synchronous;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
@Component
public class CustomSpringEventPublisher {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void publishEvent(final String message) {
System.out.println("Publishing custom event. ");
final CustomSpringEvent customSpringEvent = new CustomSpringEvent(this, message);
applicationEventPublisher.publishEvent(customSpringEvent);
}
public void publishGenericEvent(final String message, boolean success) {
System.out.println("Publishing generic event.");
final GenericSpringEvent<String> genericSpringEvent = new GenericStringSpringEvent(message, success);
applicationEventPublisher.publishEvent(genericSpringEvent);
}
public void publishGenericAppEvent(final String message) {
System.out.println("Publishing generic event.");
final GenericSpringAppEvent<String> genericSpringEvent = new GenericStringSpringAppEvent(this, message);
applicationEventPublisher.publishEvent(genericSpringEvent);
}
}
@@ -0,0 +1,18 @@
package org.baeldung.springevents.synchronous;
import org.springframework.context.ApplicationEvent;
public class GenericSpringAppEvent<T> extends ApplicationEvent {
private final T what;
public GenericSpringAppEvent(final Object source, final T what) {
super(source);
this.what = what;
}
public T getWhat() {
return what;
}
}
@@ -0,0 +1,21 @@
package org.baeldung.springevents.synchronous;
public class GenericSpringEvent<T> {
private final T what;
protected final boolean success;
public GenericSpringEvent(final T what, final boolean success) {
this.what = what;
this.success = success;
}
public T getWhat() {
return what;
}
public boolean isSuccess() {
return success;
}
}
@@ -0,0 +1,22 @@
package org.baeldung.springevents.synchronous;
import org.springframework.context.ApplicationListener;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
@Component
public class GenericSpringEventListener implements ApplicationListener<GenericSpringAppEvent<String>> {
// for testing
private boolean hitEventHandler = false;
@Override
public void onApplicationEvent(@NonNull final GenericSpringAppEvent<String> event) {
System.out.println("Received spring generic event - " + event.getWhat());
hitEventHandler = true;
}
boolean isHitEventHandler() {
return hitEventHandler;
}
}
@@ -0,0 +1,9 @@
package org.baeldung.springevents.synchronous;
class GenericStringSpringAppEvent extends GenericSpringAppEvent<String> {
GenericStringSpringAppEvent(final Object source, final String what) {
super(source, what);
}
}
@@ -0,0 +1,9 @@
package org.baeldung.springevents.synchronous;
public class GenericStringSpringEvent extends GenericSpringEvent<String> {
GenericStringSpringEvent(final String what, final boolean success) {
super(what, success);
}
}
@@ -0,0 +1,10 @@
package org.baeldung.springevents.synchronous;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("org.baeldung.springevents.synchronous")
public class SynchronousSpringEventsConfig {
}
@@ -0,0 +1,35 @@
package org.baeldung.startup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
@Scope(value = "prototype")
public class AllStrategiesExampleBean implements InitializingBean {
private static final Logger LOG = LoggerFactory.getLogger(AllStrategiesExampleBean.class);
public AllStrategiesExampleBean() {
LOG.info("Constructor");
}
@Override
public void afterPropertiesSet() throws Exception {
LOG.info("InitializingBean");
}
@PostConstruct
public void postConstruct() {
LOG.info("PostConstruct");
}
public void init() {
LOG.info("init-method");
}
}
@@ -0,0 +1,21 @@
package org.baeldung.startup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class EventListenerExampleBean {
private static final Logger LOG = LoggerFactory.getLogger(EventListenerExampleBean.class);
public static int counter;
@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
LOG.info("Increment counter");
counter++;
}
}
@@ -0,0 +1,24 @@
package org.baeldung.startup;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
@Scope(value = "prototype")
public class InitMethodExampleBean {
private static final Logger LOG = LoggerFactory.getLogger(InitMethodExampleBean.class);
@Autowired
private Environment environment;
public void init() {
LOG.info("Env Default Profiles", Arrays.asList(environment.getDefaultProfiles()));
}
}
@@ -0,0 +1,26 @@
package org.baeldung.startup;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
@Scope(value = "prototype")
public class InitializingBeanExampleBean implements InitializingBean {
private static final Logger LOG = LoggerFactory.getLogger(InitializingBeanExampleBean.class);
@Autowired
private Environment environment;
@Override
public void afterPropertiesSet() throws Exception {
LOG.info("Env Default Profiles", Arrays.asList(environment.getDefaultProfiles()));
}
}
@@ -0,0 +1,18 @@
package org.baeldung.startup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class InvalidInitExampleBean {
@Autowired
private Environment environment;
public InvalidInitExampleBean() {
environment.getActiveProfiles();
}
}
@@ -0,0 +1,22 @@
package org.baeldung.startup;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
@Scope(value = "prototype")
public class LogicInConstructorExampleBean {
private static final Logger LOG = LoggerFactory.getLogger(LogicInConstructorExampleBean.class);
@Autowired
public LogicInConstructorExampleBean(Environment environment) {
LOG.info("Env Default Profiles", Arrays.asList(environment.getDefaultProfiles()));
}
}
@@ -0,0 +1,27 @@
package org.baeldung.startup;
import java.util.Arrays;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
@Scope(value = "prototype")
public class PostConstructExampleBean {
private static final Logger LOG = LoggerFactory.getLogger(PostConstructExampleBean.class);
@Autowired
private Environment environment;
@PostConstruct
public void init() {
LOG.info("Env Default Profiles", Arrays.asList(environment.getDefaultProfiles()));
}
}
@@ -0,0 +1,9 @@
package org.baeldung.startup;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("org.baeldung.startup")
public class SpringStartupConfig {
}
@@ -0,0 +1,22 @@
package org.baeldung.startup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class StartupApplicationListenerExample implements ApplicationListener<ContextRefreshedEvent> {
private static final Logger LOG = LoggerFactory.getLogger(StartupApplicationListenerExample.class);
public static int counter;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
LOG.info("Increment counter");
counter++;
}
}
@@ -0,0 +1 @@
spring.profiles.active=@spring.profiles.active@
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="ship" class="org.baeldung.bean.injection.Ship">
<constructor-arg>
<ref bean="helm"/>
</constructor-arg>
</bean>
<bean id="helm" class="org.baeldung.bean.injection.Helm"/>
</beans>
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="ship" class="org.baeldung.bean.injection.Ship">
<property name="helm">
<ref bean="helm"/>
</property>
</bean>
<bean id="helm" class="org.baeldung.bean.injection.Helm"/>
</beans>
@@ -0,0 +1,7 @@
CREATE TABLE EMPLOYEE
(
ID int NOT NULL PRIMARY KEY,
FIRST_NAME varchar(255),
LAST_NAME varchar(255),
ADDRESS varchar(255),
);
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>
<bean id="employeeDao" class="org.baeldung.jdbc.EmployeeDAO">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<context:property-placeholder location="jdbc.properties"/>
</beans>
@@ -0,0 +1,7 @@
INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling', 'Canada');
INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth', 'USA');
INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds', 'Finland');
INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie', 'USA');
@@ -0,0 +1,11 @@
rootLogger.level=info
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT
appenders=console
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %p %d{yyyy-MM-dd} [%t] %c{1} - %msg%n
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN"/>
<logger name="org.springframework.transaction" level="WARN"/>
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN"/>
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="personSingleton" class="org.baeldung.scopes.Person" scope="singleton"/>
<bean id="personPrototype" class="org.baeldung.scopes.Person" scope="prototype"/>
</beans>
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>
<beans profile="dev">
<bean id="devDatasourceConfig" class="org.baeldung.profiles.DevDatasourceConfig"/>
</beans>
<beans profile="production">
<bean id="productionDatasourceConfig" class="org.baeldung.profiles.ProductionDatasourceConfig"/>
</beans>
</beans>
@@ -0,0 +1,16 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="initMethodExampleBean"
class="org.baeldung.startup.InitMethodExampleBean"
scope="prototype"
init-method="init">
</bean>
<bean id="allStrategiesExampleBean"
class="org.baeldung.startup.AllStrategiesExampleBean"
init-method="init">
</bean>
</beans>
@@ -0,0 +1,22 @@
package org.baeldung.autowire.sample;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
public class FooServiceIntegrationTest {
@Autowired
FooService fooService;
@Test
public void whenFooFormatterType_thenReturnFoo() {
Assert.assertEquals("foo", fooService.doStuff());
}
}
@@ -0,0 +1,21 @@
package org.baeldung.bean.injection;
import org.baeldung.bean.config.ConstructorBasedShipConfig;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ConstructorBasedBeanInjectionWithJavaConfigIntegrationTest {
private static final String HELM_NAME = "HelmBrand";
@Test
public void givenJavaConfigFile_whenUsingConstructorBasedBeanInjection_thenCorrectHelmName() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ConstructorBasedShipConfig.class);
ctx.refresh();
Ship ship = ctx.getBean(Ship.class);
Assert.assertEquals(HELM_NAME, ship.getHelm().getBrandOfHelm());
}
}
@@ -0,0 +1,19 @@
package org.baeldung.bean.injection;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ConstructorBasedBeanInjectionWithXMLConfigIntegrationTest {
private static final String HELM_NAME = "HelmBrand";
@Test
public void givenXMLConfigFile_whenUsingConstructorBasedBeanInjection_thenCorrectHelmName() {
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beanInjection-constructor.xml");
final Ship shipConstructorBean = (Ship) applicationContext.getBean("ship");
Assert.assertEquals(HELM_NAME, shipConstructorBean.getHelm().getBrandOfHelm());
}
}
@@ -0,0 +1,23 @@
package org.baeldung.bean.injection;
import org.baeldung.bean.config.SetterBasedShipConfig;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SetterBasedBeanInjectionWithJavaConfigIntegrationTest {
private static final String HELM_NAME = "HelmBrand";
@Test
public void givenJavaConfigFile_whenUsingSetterBasedBeanInjection_thenCorrectHelmName() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(SetterBasedShipConfig.class);
ctx.refresh();
Ship ship = ctx.getBean(Ship.class);
Assert.assertEquals(HELM_NAME, ship.getHelm().getBrandOfHelm());
}
}
@@ -0,0 +1,19 @@
package org.baeldung.bean.injection;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SetterBasedBeanInjectionWithXMLConfigIntegrationTest {
private static final String HELM_NAME = "HelmBrand";
@Test
public void givenXMLConfigFile_whenUsingSetterBasedBeanInjection_thenCorrectHelmName() {
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beanInjection-setter.xml");
final Ship shipSetterBean = (Ship) applicationContext.getBean("ship");
Assert.assertEquals(HELM_NAME, shipSetterBean.getHelm().getBrandOfHelm());
}
}
@@ -0,0 +1,40 @@
package org.baeldung.customannotation;
import java.io.Serializable;
public class Account implements Serializable {
private static final long serialVersionUID = 7857541629844398625L;
private Long id;
private String email;
private Person person;
public Account() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
@@ -0,0 +1,18 @@
package org.baeldung.customannotation;
import org.springframework.stereotype.Repository;
@Repository
public class BeanWithGenericDAO {
@DataAccess(entity = Person.class)
private GenericDAO<Person> personGenericDAO;
public BeanWithGenericDAO() {
}
public GenericDAO<Person> getPersonGenericDAO() {
return personGenericDAO;
}
}
@@ -0,0 +1,57 @@
package org.baeldung.customannotation;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { CustomAnnotationConfiguration.class })
public class DataAccessAnnotationIntegrationTest {
@DataAccess(entity = Person.class)
private GenericDAO<Person> personGenericDAO;
@DataAccess(entity = Account.class)
private GenericDAO<Account> accountGenericDAO;
@DataAccess(entity = Person.class)
private GenericDAO<Person> anotherPersonGenericDAO;
@Test
public void whenGenericDAOInitialized_thenNotNull() {
assertThat(personGenericDAO, is(notNullValue()));
assertThat(accountGenericDAO, is(notNullValue()));
}
@Test
public void whenGenericDAOInjected_thenItIsSingleton() {
assertThat(personGenericDAO, not(sameInstance(accountGenericDAO)));
assertThat(personGenericDAO, not(equalTo(accountGenericDAO)));
assertThat(personGenericDAO, sameInstance(anotherPersonGenericDAO));
}
@Test
public void whenFindAll_thenMessagesIsCorrect() {
personGenericDAO.findAll();
assertThat(personGenericDAO.getMessage(), is("Would create findAll query from Person"));
accountGenericDAO.findAll();
assertThat(accountGenericDAO.getMessage(), is("Would create findAll query from Account"));
}
@Test
public void whenPersist_thenMakeSureThatMessagesIsCorrect() {
personGenericDAO.persist(new Person());
assertThat(personGenericDAO.getMessage(), is("Would create persist query from Person"));
accountGenericDAO.persist(new Account());
assertThat(accountGenericDAO.getMessage(), is("Would create persist query from Account"));
}
}

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