View Javadoc
1   package org.imageconverter.util;
2   
3   import java.util.Objects;
4   
5   import org.springframework.beans.factory.ObjectProvider;
6   import org.springframework.context.ApplicationContext;
7   import org.springframework.context.ApplicationContextAware;
8   import org.springframework.core.env.Environment;
9   import org.springframework.stereotype.Component;
10  
11  /**
12   * Utils to retrieves spring objects to non managed objects.
13   * 
14   * @author Fernando Romulo da Silva
15   */
16  @Component
17  public class BeanUtil implements ApplicationContextAware {
18  
19      private static ApplicationContext context;
20  
21      /**
22       * Set the spring context to retrive objects.
23       * 
24       * @param newContext The new context
25       */
26      public static void defineContext(final ApplicationContext newContext) {
27  
28  	if (Objects.isNull(context)) {
29  	    context = newContext;
30  	}
31      }
32  
33      /**
34       * Get a bean from its type.
35       * 
36       * @param <T>       The type
37       * @param beanClass The class type
38       * @return A bean retrieved
39       */
40      public static <T> T getBeanFrom(final Class<T> beanClass) {
41  	return context.getBean(beanClass);
42      }
43  
44      /**
45       * Get a bean provider (factory) from its type.
46       * 
47       * @param <T>       The type
48       * @param beanClass The class type
49       * @return A bean retrieved
50       */
51      public static <T> ObjectProvider<T> getBeanProviderFrom(final Class<T> beanClass) {
52  	return context.getBeanProvider(beanClass);
53      }
54  
55      /**
56       * Get the context environment
57       * 
58       * @return A {@link Environment} object
59       */
60      public static Environment getEnvironment() {
61  	return context.getEnvironment();
62      }
63  
64      /**
65       * Get the property value.
66       * 
67       * @param key The property value
68       * @return The String value property
69       */
70      public static String getPropertyValue(final String key) {
71  	return context.getEnvironment().getProperty(key);
72      }
73  
74      /**
75       * {@inheritDoc}
76       */
77      @Override
78      public void setApplicationContext(final ApplicationContext applicationContext) {
79  	defineContext(applicationContext);
80      }
81  }