be.redlab.context.spring.support.AutowiredFieldSetter.java Source code

Java tutorial

Introduction

Here is the source code for be.redlab.context.spring.support.AutowiredFieldSetter.java

Source

/*
 * Copyright 2012 Balder Van Camp
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
package be.redlab.context.spring.support;

import java.lang.reflect.Field;

import org.springframework.beans.factory.annotation.Autowired;

import be.redlab.context.ApplicationContext;
import be.redlab.context.load.UnsettableFieldException;
import be.redlab.context.load.ri.DefaultFieldSetter;

/**
 * The AutowiredFieldSetters extends from the DefaultFieldSetter and supports classes that have an
 * <code>@Autowired</code> annotation from Spring.
 *
 * @author redlab
 *
 */
public class AutowiredFieldSetter extends DefaultFieldSetter {

    /**
     * {@inheritDoc} First calls {@link DefaultFieldSetter#getValue} method if the value is not found.
     *
     * @throws UnsettableFieldException
     */
    @Override
    protected Object getValue(final Field f, final Object o, final ApplicationContext context)
            throws UnsettableFieldException {
        Object value = null;
        value = super.getValue(f, o, context);
        if (null == value) {
            Autowired auto = f.getAnnotation(Autowired.class);
            if (null != auto) {
                value = context.find(f.getType());
                setApplicationContext(f, context, value);
                if (null == value && auto.required()) {
                    throw new UnsettableFieldException(String.format("Required field %s could not be set for %s",
                            f.getName(), o.getClass().getName()));
                }
            }
        }
        return value;
    }
}