2.1 默认方法(default method)
- java8引入了一个
default medthod
; - 用来扩展已有的接口,在对已有接口的使用不产生任何影响的情况下,添加扩展
- 使用
default
关键字 - Spring 4.2支持加载在默认方法里声明的bean
2.2
- 将要被声明成bean的类
public class DemoService {
public void doSomething(){
System.out.println("find bean in default method");
}
}
- 在接口的默认方法里定义bean
package com.wisely.spring4_2.defaultMethod;
import org.springframework.context.annotation.Bean;
public interface DemoServiceConfig {
@Bean
default DemoService DemoService(){
return new DemoService();
}
}
- 配置类
package com.wisely.spring4_2.defaultMethod;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig implements DemoServiceConfig{
}
- 运行
package com.wisely.spring4_2.defaultMethod;
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
新书推荐《JavaEE开发的颠覆者: Spring Boot实战》,涵盖Spring 4.x、Spring MVC 4.x、Spring Boot企业开发实战。
京东地址:http://item.jd.com/11894632.html
当当地址:http://product.dangdang.com/23926195.html
亚马逊地址:http://www.amazon.cn/图书/dp/B01D5ZBFUK/ref=zg_bsnr_663834051_6
淘宝地址:https://item.taobao.com/item.htm?id=528426235744&ns=1&abbucket=8#detail
或自己在京东、淘宝、亚马逊、当当、互动出版社搜索自选。