Skip to content

Commit 1ef53e2

Browse files
author
Eugen
committed
Merge pull request eugenp#269 from xsalefter/master
Initial commit for "Spring Custom Annotation with Dynamic Qualifier"
2 parents 6aec841 + 32ea1e0 commit 1ef53e2

10 files changed

Lines changed: 394 additions & 0 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package org.baeldung.customannotation;
2+
3+
import org.springframework.context.annotation.ComponentScan;
4+
import org.springframework.context.annotation.Configuration;
5+
6+
@Configuration
7+
@ComponentScan("org.baeldung.customannotation")
8+
public class CustomAnnotationConfiguration {
9+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package org.baeldung.customannotation;
2+
3+
import java.lang.annotation.Documented;
4+
import java.lang.annotation.ElementType;
5+
import java.lang.annotation.Retention;
6+
import java.lang.annotation.RetentionPolicy;
7+
import java.lang.annotation.Target;
8+
9+
@Retention(RetentionPolicy.RUNTIME)
10+
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
11+
@Documented
12+
public @interface DataAccess {
13+
Class<?>entity();
14+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package org.baeldung.customannotation;
2+
3+
import org.springframework.beans.BeansException;
4+
import org.springframework.beans.factory.annotation.Autowired;
5+
import org.springframework.beans.factory.config.BeanPostProcessor;
6+
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
7+
import org.springframework.stereotype.Component;
8+
import org.springframework.util.ReflectionUtils;
9+
import org.springframework.util.ReflectionUtils.FieldCallback;
10+
11+
@Component
12+
public class DataAccessAnnotationProcessor implements BeanPostProcessor {
13+
14+
private ConfigurableListableBeanFactory configurableListableBeanFactory;
15+
16+
@Autowired
17+
public DataAccessAnnotationProcessor(ConfigurableListableBeanFactory bf) {
18+
configurableListableBeanFactory = bf;
19+
}
20+
21+
@Override
22+
public Object postProcessBeforeInitialization(Object bean, String beanName)
23+
throws BeansException {
24+
scanDataAccessAnnotation(bean, beanName);
25+
return bean;
26+
}
27+
28+
@Override
29+
public Object postProcessAfterInitialization(Object bean, String beanName)
30+
throws BeansException {
31+
return bean;
32+
}
33+
34+
protected void scanDataAccessAnnotation(Object bean, String beanName) {
35+
Class<?> managedBeanClass = bean.getClass();
36+
FieldCallback fcb = new DataAccessFieldCallback(configurableListableBeanFactory, bean);
37+
ReflectionUtils.doWithFields(managedBeanClass, fcb);
38+
}
39+
}
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
package org.baeldung.customannotation;
2+
3+
import java.lang.reflect.Constructor;
4+
import java.lang.reflect.Field;
5+
import java.lang.reflect.ParameterizedType;
6+
import java.lang.reflect.Type;
7+
8+
import org.slf4j.Logger;
9+
import org.slf4j.LoggerFactory;
10+
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
11+
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
12+
import org.springframework.util.ReflectionUtils;
13+
import org.springframework.util.ReflectionUtils.FieldCallback;
14+
15+
16+
public final class DataAccessFieldCallback implements FieldCallback {
17+
18+
private static Logger logger = LoggerFactory.getLogger(DataAccessFieldCallback.class);
19+
private static int AUTOWIRE_MODE = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
20+
21+
private static String ERROR_ENTITY_VALUE_NOT_SAME = "@DataAccess(entity) "
22+
+ "value should have same type with injected generic type.";
23+
private static String WARN_NON_GENERIC_VALUE = "@DataAccess annotation assigned "
24+
+ "to raw (non-generic) declaration. This will make your code less type-safe.";
25+
private static String ERROR_CREATE_INSTANCE = "Cannot create instance of "
26+
+ "type '{}' or instance creation is failed because: {}";
27+
28+
private ConfigurableListableBeanFactory configurableListableBeanFactory;
29+
private Object bean;
30+
31+
public DataAccessFieldCallback(final ConfigurableListableBeanFactory bf, final Object bean) {
32+
configurableListableBeanFactory = bf;
33+
this.bean = bean;
34+
}
35+
36+
@Override
37+
public void doWith(final Field field)
38+
throws IllegalArgumentException, IllegalAccessException {
39+
if (!field.isAnnotationPresent(DataAccess.class)) {
40+
return;
41+
}
42+
ReflectionUtils.makeAccessible(field);
43+
final Type fieldGenericType = field.getGenericType();
44+
// In this example, get actual "GenericDAO' type.
45+
final Class<?> generic = field.getType();
46+
final Class<?> classValue = field.getDeclaredAnnotation(DataAccess.class).entity();
47+
48+
if (genericTypeIsValid(classValue, fieldGenericType)) {
49+
final String beanName = classValue.getSimpleName() + generic.getSimpleName();
50+
final Object beanInstance = getBeanInstance(beanName, generic, classValue);
51+
field.set(bean, beanInstance);
52+
} else {
53+
throw new IllegalArgumentException(ERROR_ENTITY_VALUE_NOT_SAME);
54+
}
55+
}
56+
57+
58+
/**
59+
* For example, if user write:
60+
* <pre>
61+
* &#064;DataAccess(entity=Person.class)
62+
* private GenericDAO&lt;Account&gt; personGenericDAO;
63+
* </pre>
64+
* then this is should be failed.
65+
*/
66+
public boolean genericTypeIsValid(final Class<?> clazz, final Type field) {
67+
if (field instanceof ParameterizedType) {
68+
final ParameterizedType parameterizedType = (ParameterizedType) field;
69+
final Type type = parameterizedType.getActualTypeArguments()[0];
70+
71+
return type.equals(clazz);
72+
} else {
73+
logger.warn(WARN_NON_GENERIC_VALUE);
74+
return true;
75+
}
76+
}
77+
78+
79+
80+
public final Object getBeanInstance(final String beanName, final Class<?> genericClass, final Class<?> paramClass) {
81+
Object daoInstance = null;
82+
if (!configurableListableBeanFactory.containsBean(beanName)) {
83+
logger.info("Creating new DataAccess bean named '{}'.", beanName);
84+
85+
Object toRegister = null;
86+
try {
87+
final Constructor<?> ctr = genericClass.getConstructor(Class.class);
88+
toRegister = ctr.newInstance(paramClass);
89+
} catch (final Exception e) {
90+
logger.error(ERROR_CREATE_INSTANCE, genericClass.getTypeName(), e);
91+
throw new RuntimeException(e);
92+
}
93+
94+
daoInstance = configurableListableBeanFactory.initializeBean(toRegister, beanName);
95+
configurableListableBeanFactory.autowireBeanProperties(daoInstance, AUTOWIRE_MODE, true);
96+
configurableListableBeanFactory.registerSingleton(beanName, daoInstance);
97+
logger.info("Bean named '{}' created successfully.", beanName);
98+
} else {
99+
daoInstance = configurableListableBeanFactory.getBean(beanName);
100+
logger.info("Bean named '{}' already exist used as current bean reference.", beanName);
101+
}
102+
return daoInstance;
103+
}
104+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package org.baeldung.customannotation;
2+
3+
import java.util.Collections;
4+
import java.util.List;
5+
import java.util.Optional;
6+
7+
public class GenericDAO<E> {
8+
9+
private Class<E> entityClass;
10+
private String message;
11+
12+
public GenericDAO(Class<E> entityClass) {
13+
this.entityClass = entityClass;
14+
}
15+
16+
public List<E> findAll() {
17+
message = "Would create findAll query from " + entityClass.getSimpleName();
18+
return Collections.emptyList();
19+
}
20+
21+
public Optional<E> persist(E toPersist) {
22+
message = "Would create persist query from " + toPersist.getClass().getSimpleName();
23+
return Optional.empty();
24+
}
25+
26+
/** Only used for unit-testing. */
27+
public final String getMessage() {
28+
return message;
29+
}
30+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package org.baeldung.customannotation;
2+
3+
import java.io.Serializable;
4+
5+
public class Account implements Serializable {
6+
7+
private static final long serialVersionUID = 7857541629844398625L;
8+
9+
private Long id;
10+
private String email;
11+
private Person person;
12+
13+
public Account() {
14+
}
15+
16+
public Long getId() {
17+
return id;
18+
}
19+
20+
public void setId(Long id) {
21+
this.id = id;
22+
}
23+
24+
public String getEmail() {
25+
return email;
26+
}
27+
28+
public void setEmail(String email) {
29+
this.email = email;
30+
}
31+
32+
public Person getPerson() {
33+
return person;
34+
}
35+
36+
public void setPerson(Person person) {
37+
this.person = person;
38+
}
39+
40+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package org.baeldung.customannotation;
2+
3+
import org.springframework.stereotype.Repository;
4+
5+
@Repository
6+
public class BeanWithGenericDAO {
7+
8+
@DataAccess(entity=Person.class)
9+
private GenericDAO<Person> personGenericDAO;
10+
11+
public BeanWithGenericDAO() {}
12+
13+
public GenericDAO<Person> getPersonGenericDAO() {
14+
return personGenericDAO;
15+
}
16+
17+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package org.baeldung.customannotation;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.CoreMatchers.is;
5+
import static org.hamcrest.CoreMatchers.not;
6+
import static org.hamcrest.CoreMatchers.notNullValue;
7+
import static org.hamcrest.CoreMatchers.sameInstance;
8+
import static org.junit.Assert.assertThat;
9+
10+
import org.junit.Test;
11+
import org.junit.runner.RunWith;
12+
import org.springframework.test.context.ContextConfiguration;
13+
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
14+
15+
@RunWith(SpringJUnit4ClassRunner.class)
16+
@ContextConfiguration(classes = { CustomAnnotationConfiguration.class })
17+
public class DataAccessAnnotationTest {
18+
19+
@DataAccess(entity = Person.class)
20+
private GenericDAO<Person> personGenericDAO;
21+
@DataAccess(entity = Account.class)
22+
private GenericDAO<Account> accountGenericDAO;
23+
@DataAccess(entity = Person.class)
24+
private GenericDAO<Person> anotherPersonGenericDAO;
25+
26+
@Test
27+
public void whenGenericDAOInitialized_thenNotNull() {
28+
assertThat(personGenericDAO, is(notNullValue()));
29+
assertThat(accountGenericDAO, is(notNullValue()));
30+
}
31+
32+
@Test
33+
public void whenGenericDAOInjected_thenItIsSingleton() {
34+
assertThat(personGenericDAO, not(sameInstance(accountGenericDAO)));
35+
assertThat(personGenericDAO, not(equalTo(accountGenericDAO)));
36+
37+
assertThat(personGenericDAO, sameInstance(anotherPersonGenericDAO));
38+
}
39+
40+
@Test
41+
public void whenFindAll_thenMessagesIsCorrect() {
42+
personGenericDAO.findAll();
43+
assertThat(personGenericDAO.getMessage(), is("Would create findAll query from Person"));
44+
45+
accountGenericDAO.findAll();
46+
assertThat(accountGenericDAO.getMessage(), is("Would create findAll query from Account"));
47+
}
48+
49+
@Test
50+
public void whenPersist_thenMakeSureThatMessagesIsCorrect() {
51+
personGenericDAO.persist(new Person());
52+
assertThat(personGenericDAO.getMessage(), is("Would create persist query from Person"));
53+
54+
accountGenericDAO.persist(new Account());
55+
assertThat(accountGenericDAO.getMessage(), is("Would create persist query from Account"));
56+
}
57+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package org.baeldung.customannotation;
2+
3+
import static org.hamcrest.CoreMatchers.is;
4+
import static org.hamcrest.CoreMatchers.notNullValue;
5+
import static org.junit.Assert.assertThat;
6+
7+
import java.lang.reflect.Type;
8+
9+
import org.junit.Rule;
10+
import org.junit.Test;
11+
import org.junit.rules.ExpectedException;
12+
import org.junit.runner.RunWith;
13+
import org.springframework.beans.factory.annotation.Autowired;
14+
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
15+
import org.springframework.test.context.ContextConfiguration;
16+
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
17+
18+
19+
@RunWith(SpringJUnit4ClassRunner.class)
20+
@ContextConfiguration(classes = { CustomAnnotationConfiguration.class })
21+
public class DataAccessFieldCallbackTest {
22+
23+
@Autowired
24+
private ConfigurableListableBeanFactory configurableListableBeanFactory;
25+
26+
@Autowired
27+
private BeanWithGenericDAO beanWithGenericDAO;
28+
29+
@Rule
30+
public ExpectedException ex = ExpectedException.none();
31+
32+
@Test
33+
public void whenObjectCreated_thenObjectCreationIsSuccessful() {
34+
final DataAccessFieldCallback dataAccessFieldCallback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO);
35+
assertThat(dataAccessFieldCallback, is(notNullValue()));
36+
}
37+
38+
@Test
39+
public void whenMethodGenericTypeIsValidCalled_thenReturnCorrectValue()
40+
throws NoSuchFieldException, SecurityException {
41+
final DataAccessFieldCallback callback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO);
42+
final Type fieldType = BeanWithGenericDAO.class.getDeclaredField("personGenericDAO").getGenericType();
43+
final boolean result = callback.genericTypeIsValid(Person.class, fieldType);
44+
assertThat(result, is(true));
45+
}
46+
47+
@Test
48+
public void whenMethodGetBeanInstanceCalled_thenReturnCorrectInstance() {
49+
final DataAccessFieldCallback callback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO);
50+
final Object result = callback.getBeanInstance("personGenericDAO", GenericDAO.class, Person.class);
51+
assertThat((result instanceof GenericDAO), is(true));
52+
}
53+
}

0 commit comments

Comments
 (0)