Closed
Description
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:
- @Configuration interface with Java 8 default methods (as a standalone artifact) [SPR-14220] #18794
@Configuration
interface with Java 8 default methods (as a standalone artifact) - Java based config should support class-only component declarations through @Import [SPR-11740] #16362 Java based config should support class-only component declarations through
@Import
- Make ReflectionUtils.doWithMethods work on Java 8 default interface methods [SPR-12822] #17419 Make ReflectionUtils.doWithMethods work on Java 8 default interface methods
- Java 8 default methods not detected as bean properties [SPR-14198] #18772 Java 8 default methods not detected as bean properties
- Provide access to the return type in MethodMetadata [SPR-13024] #17615 Provide access to the return type in MethodMetadata
Referenced from: commits 1924629
4 votes, 11 watchers