Skip to content

@Bean on Java 8 default methods in interfaces [SPR-10919] #15547

Closed
@spring-projects-issues

Description

@spring-projects-issues

Thomas Darimont opened SPR-10919 and commented

It would be great if the JavaConfig configuration style would support the definition of @Bean Bean-Definitions via Java 8's default methods.

To get this working it is necessary, that default methods are also considered while scanning a type for @Bean Bean-Definitions.

Here is a small example on how this would look like:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class InterfaceBasedJavaConfigExample {

    interface Service0 {}

    interface Service1 {}

    interface DataStore {}

    interface PersistenceConfig {
        @Bean
        default DataStore dataStore() {
            return mock(DataStore.class);
        }
    }

    interface ServiceConfig {
        @Bean
        default Service1 service1() {
            return mock(Service1.class);
        }
    }

    static class Application {

        final Service0 service0;
        final Service1 service1;
        final DataStore dataStore;

        @Autowired
        public Application(Service0 service0, Service1 service1, DataStore dataStore) {
            this.service0 = service0;
            this.service1 = service1;
            this.dataStore = dataStore;
        }
    }

    @Configuration
    static class ApplicationConfig implements ServiceConfig, PersistenceConfig {

        @Bean
        public Service0 service0() {
            return mock(Service0.class);
        }

        @Bean
        public Application application() {
            return new Application(service0(), service1(), dataStore());
        }
    }

    @Autowired
    Application application;

    @Test
    public void bootstrap() {
        assertNotNull("app should not be null", application);
        assertNotNull("app.dataStore should not be null", application.dataStore);
        assertNotNull("app.service1 should not be null", application.service1);
    }
}

Affects: 4.0 M3

Issue Links:

Referenced from: commits 1924629

4 votes, 11 watchers

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions