/*
 * 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.plugin.context.annotationconfig;

import static org.junit.Assert.*;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.config.java.annotation.Bean;
import org.springframework.config.java.annotation.Configuration;
import org.springframework.config.java.context.JavaConfigApplicationContext;
import org.springframework.config.java.plugin.context.AnnotationDrivenConfig;


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

    @Test
    public void testAutowiredAnnotationIsRespected() {
        JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(Config.class);
        AccountService accountService = ctx.getBean(AccountService.class);
        assertNotNull("AccountRepository was not autowired into AccountService", accountService.accountRepository);
    }

    @Configuration
    @AnnotationDrivenConfig
    static class Config {
        public @Bean AccountService accountService() {
            return new AccountService();
        }

        public @Bean AccountRepository accountRepository() {
            return new AccountRepository();
        }
    }

    static class AccountService {
        private AccountRepository accountRepository;

        @Autowired
        public void init(AccountRepository accountRepository) {
            this.accountRepository = accountRepository;
        }
    }

    static class AccountRepository { }


    @Test
    public void testJsr250Annotations() {
        JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(Jsr250Config.class);
        Foo foo = ctx.getBean(Foo.class);
        assertTrue("@PostConstruct was not called as expected", foo.initialized);
        ctx.destroy();
        assertTrue("@PreDestroy was not called as expected", foo.destroyed);
    }

    @Configuration
    @AnnotationDrivenConfig
    static class Jsr250Config {
        public @Bean Foo foo() {
            return new Foo();
        }
    }

    static class Foo {
        boolean initialized = false;
        boolean destroyed = false;

        @PostConstruct
        public void init() {
            initialized = true;
        }

        @PreDestroy
        public void destroy() {
            destroyed = true;
        }
    }

}
