2.1 默认方法(default method)
- java8引入了一个
default medthod
; - 用来扩展已有的接口,在对已有接口的使用不产生任何影响的情况下,添加扩展
- 使用
default
关键字 - Spring 4.2.3支持加载在默认方法里声明的bean
2.2
public class DemoService {
public void doSomething(){
System.out.println("find bean in default method");
}
}
package com.wisely.spring4_2.3defaultMethod;
import org.springframework.context.annotation.Bean;
public interface DemoServiceConfig {
@Bean(name="demoService")
default DemoService DemoService(){
return new DemoService();
}
}
package com.wisely.spring4_2.3defaultMethod;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig implements DemoServiceConfig{
}
package com.wisely.spring4_2.3defaultMethod;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext("com.wisely.spring4_2.defaultMethod");
DemoService ds = context.getBean(DemoService.class);
ds.doSomething();
}
}
find bean in default method