2. Spring 4.2.3前瞻-对java8默认方法(default method)定义Bean的支持

2.1 默认方法(default method)

  • java8引入了一个default medthod;
  • 用来扩展已有的接口,在对已有接口的使用不产生任何影响的情况下,添加扩展
  • 使用default关键字
  • Spring 4.2.3支持加载在默认方法里声明的bean

2.2

  • 将要被声明成bean的类
public class DemoService {
    public void doSomething(){
        System.out.println("find bean in default method");
    }
}
  • 在接口的默认方法里定义bean
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值