Spring Boot 1.5.9与2.0.2私有实现Bean注入差异原因及修复方案
Spring Boot 2.0.2私有实现类Bean装配异常问题
当Spring尝试装配一个拥有public接口和private实现类的Bean时,Spring Boot 2.0.2会抛出非法访问异常,具体栈跟踪如下:
Caused by: java.lang.IllegalAccessException: Class kotlin.reflect.jvm.internal.FunctionCaller$Constructor can not access a member of class com.example.demo.MyCompImpl with modifiers "public" at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102) ~[na:1.8.0_112] at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:296) ~[na:1.8.0_112] at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:288) ~[na:1.8.0_112] at java.lang.reflect.Constructor.newInstance(Constructor.java:413) ~[na:1.8.0_112] at kotlin.reflect.jvm.internal.FunctionCaller$Constructor.call(FunctionCaller.kt:66) ~[kotlin-reflect-1.2.41.jar:1.2.41-release-74 (1.2.41)] at kotlin.reflect.jvm.internal.KCallableImpl.call(KCallableImpl.kt:107) ~[kotlin-reflect-1.2.41.jar:1.2.41-release-74 (1.2.41)] ... 22 common frames omitted
版本差异对比
- Spring Boot 1.5.9:该场景下Bean装配流程正常,无任何异常抛出
- Spring Boot 2.0.2:触发
IllegalAccessException,无法完成私有实现类的Bean初始化与装配
问题复现代码示例
package com.example.demo import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.builder.SpringApplicationBuilder import org.springframework.stereotype.Component @SpringBootApplication class DemoApplication fun main(args: Array<String>) { SpringApplicationBuilder(DemoApplication::class.java).run(*args) } interface ValueProvider { fun provideValue(): Double } @Component private class ValueProviderImpl(): ValueProvider { override fun provideValue() = 3.1415 } interface MyComp { fun getValue(): Double } @Component private class MyCompImpl(val provider: ValueProvider): MyComp { override fun getValue() = provider.provideValue() }
内容的提问来源于stack exchange,提问作者ohwhy
相关产品推荐
相关产品推荐

