com.greenline.hrs.admin.web.war.conf.InjectBeanPostProcessor.java Source code

Java tutorial

Introduction

Here is the source code for com.greenline.hrs.admin.web.war.conf.InjectBeanPostProcessor.java

Source

/*
 * Project: hrs-admin
 *
 * File Created at 2014/3/27
 *
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package com.greenline.hrs.admin.web.war.conf;

import com.greenline.hrs.admin.base.annotation.InjectingBean;
import com.greenline.hrs.admin.base.annotation.InjectingProperty;
import org.springframework.beans.SimpleTypeConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

@Component
public class InjectBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {

    @Autowired
    private PropertyConfigurer propertyConfigurer;

    private SimpleTypeConverter typeConverter = new SimpleTypeConverter();

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) {
        if (bean.getClass().getAnnotation(InjectingBean.class) != null) {
            injectPropertyToBean(bean);
        }
        return true;
    }

    private void injectPropertyToBean(final Object bean) {
        ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {

            @Override
            public void doWith(Field field) throws IllegalAccessException {
                InjectingProperty annotation = field.getAnnotation(InjectingProperty.class);
                if (annotation != null) {
                    Object strValue = propertyConfigurer.getProperty(annotation.value());
                    if (null != strValue) {
                        Object value = typeConverter.convertIfNecessary(strValue, field.getType());
                        ReflectionUtils.makeAccessible(field);
                        if (Modifier.isStatic(field.getModifiers())) {
                            field.set(null, value);
                        } else {
                            field.set(bean, value);
                        }
                    }
                }
            }
        });
    }
}