blu*_*ope 5 java spring spring-data-r2dbc
这是这个问题的一个例子。(弹簧数据-r2dbc)
package org.springframework.data.r2dbc.config;
@Configuration(proxyBeanMethods = false)
public abstract class AbstractR2dbcConfiguration implements ApplicationContextAware {
...
}
Run Code Online (Sandbox Code Playgroud)
按照我的常识,抽象类即使有@Configuration,也不能注册为bean。并且由于@Configuration没有@Inherited,所以继承类的对象不会自动注册为bean,所以我们必须直接为继承类添加@Configuration。我很好奇为什么有些抽象类有 @Configuration 注解,就像上面的代码一样。
我查了一些资料,发现抽象类是允许的。
\n文档中的约束并没有说抽象类或接口(可以?)不支持配置注释。
\n\n创作 @Configuration 类时的约束
\n像这个问题,希望有强者能从源码的角度解释一下这个问题。\n因为除了文档中的说明,我还不知道原因是什么。
\n反复测试了一下午,发现在抽象类上添加Configuration注解似乎没有任何效果,看起来有效的只是最终子类上的注解。
\n这是代码!!!\n首先,我们需要一个接口TestInterface.java:
public interface TestInterface { \n public String hello(); \n public String hello1(); \n} \nRun Code Online (Sandbox Code Playgroud)\n然后创建一个抽象类MyConfigration.java:
//@Configuration(proxyBeanMethods = false)\n//@Configuration\npublic abstract class MyConfigration implements TestInterface { \n @Bean \n public String hello() { \n System.out.println("call hello in super class"); \n return "hello"; \n } \n}\nRun Code Online (Sandbox Code Playgroud)\n最后,我们需要一个子类SubMyConfigration.java
@Configuration \nclass SubMyConfigration extends MyConfigration { \n @Bean \n public String hello1() { \n return " hello1 from subclass"; \n } \n} \nRun Code Online (Sandbox Code Playgroud)\n使用main方法测试:
\npublic static void main(String[] args) { \n ConfigurableApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);\n\n TestInterface configOfInterface = applicationContext.getBean(MyConfigration.class);\n configOfInterface.hello(); \n configOfInterface.hello(); \n configOfInterface.hello1(); \n configOfInterface.hello1(); \n} \nRun Code Online (Sandbox Code Playgroud)\n如果添加@Configuration(proxyBeanMethods = false)子类(SubMyConfigration),将打印call hello in super class3次。
如果添加@Configuration子类(SubMyConfigration),将打印call hello in super class1次。
@Configuration超类(MyConfigration)是否添加注解以及是否添加proxyBeanMethods = false不影响打印次数。
根据这部分代码,有3个结论\xef\xbc\x9a
\nSubMyConfigration)必须添加@Configuration,否则不起作用;@Configuration注解,以及proxyBeanMethods = false注解中是否添加参数,都不会影响最终的结果。proxyBeanMethods = false参数,只有添加到子类@Configuration注解中才会影响结果| 归档时间: |
|
| 查看次数: |
1017 次 |
| 最近记录: |