/*
 * Copyright 2002-2008 the original author or authors.
 *
 * 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 test.feature.lifecycle.callback;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import org.springframework.beans.factory.InitializingBean;

import org.springframework.config.java.annotation.Bean;
import org.springframework.config.java.annotation.Configuration;
import org.springframework.config.java.context.JavaConfigApplicationContext;

import test.common.beans.TestBean;


/** TODO: JAVADOC */
public class InitializingBeanTests {

    @Test
    public void testAfterPropertiesSetInvokedBeforeExplicitWiring() {
        JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(AfterPropertiesConfiguration.class);

        // This is enough to run the test - see assertions in test() bean method below
        ctx.getBean(TestBean.class, "test");
    }

    @Configuration
    public static class AfterPropertiesConfiguration {
        @Bean
        public TestBean test() {
            assertEquals("AfterPropertiesSet must have been called by now", 5, ib().sum());
            return new TestBean();
        }

        @Bean
        public AnInitializingBean ib() {
            AnInitializingBean ib = new AnInitializingBean();
            ib.setA(2);
            ib.setB(3);
            return ib;
        }
    }

    public static class AnInitializingBean implements InitializingBean {
        private int a, b, sum;

        public void setA(int a) { this.a = a; }

        public void setB(int b) { this.b = b; }

        public int sum() { return sum; }

        public void afterPropertiesSet() throws Exception { sum = a + b; }
    }

}
