├── .gitignore
├── LICENSE
├── README.md
├── pom.xml
├── q&a
├── 36. 自动装配的补充.jpg
└── 自动装配.md
└── src
└── main
└── java
├── com
└── example
│ └── demo
│ └── DemoApplication.java
└── example
├── aop
└── DemoAspect.java
├── conditional
├── App.java
├── ColorConditional.java
└── ColorConfiguration.java
├── config
├── App.java
└── ConfigurationDemo.java
├── customizer
└── WebMvcCustomizer.java
├── enablexxx
├── App.java
├── Black.java
├── Blue.java
├── ColorConfiguration.java
├── ColorImportBeanDefinitionRegistrar.java
├── ColorImportSelector.java
├── ColorRegistrarConfiguration.java
├── EnableColor.java
├── Green.java
├── Red.java
└── Yellow.java
├── init
├── Cat.java
└── CatBeanPostProcessor.java
├── servlet
├── DemoServlet.java
├── DemoServletRegistryBean.java
└── ServletConfiguration.java
└── transaction
└── service
├── DemoService.java
└── DemoService2.java
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled class file
2 | *.class
3 |
4 | # Log file
5 | *.log
6 |
7 | # BlueJ files
8 | *.ctxt
9 |
10 | # Mobile Tools for Java (J2ME)
11 | .mtj.tmp/
12 |
13 | # Package Files #
14 | *.jar
15 | *.war
16 | *.nar
17 | *.ear
18 | *.zip
19 | *.tar.gz
20 | *.rar
21 |
22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
23 | hs_err_pid*
24 |
25 | target/
26 | pom.xml.tag
27 | pom.xml.releaseBackup
28 | pom.xml.versionsBackup
29 | pom.xml.next
30 | release.properties
31 | dependency-reduced-pom.xml
32 | buildNumber.properties
33 | .mvn/timing.properties
34 | .mvn/wrapper/maven-wrapper.jar
35 |
36 | .idea/
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # spring-boot-source-analysis-code
2 | 掘金 《SpringBoot源码解读与原理分析》 小册测试和演示代码。
3 |
4 | 当初我写小册的时候,一直用的这一个工程,所以pom一直在变化(逃...),当然也由于研究原理通常最好是动手实践,所以我没做那种现成的,只要clone下来就能立马运行的,我这边写的也只是参考,小伙伴们最好是亲自试一试,跟着Debug走走看。小册中使用的场景都很简单,尽可能的原生,不加入过多的东西,为的就是这个。
5 |
6 | 所有的测试代码都放在src/main/java的example包下,需要哪个模块可以直接从那里头找。有一些简单的模块(config、enablexxx等)里面有个App的类,那就是不需要依赖SpringBoot启动环境来测试的,可以直接运行App的main方法测试即可。
7 |
8 | 可能存在描述的不详细的部分,欢迎小伙伴们提出需求。
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 2.1.9.RELEASE
9 |
10 | com.linkedbear
11 | spring-boot-source-analysis-code
12 | 0.0.1-SNAPSHOT
13 | spring-boot-source-analysis-code
14 |
15 |
16 | 1.8
17 |
18 |
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-starter-web
23 |
24 |
25 |
26 |
32 |
33 |
34 |
40 |
41 |
42 |
43 |
49 |
50 |
51 |
52 |
53 |
54 | org.springframework.boot
55 | spring-boot-maven-plugin
56 |
57 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/q&a/36. 自动装配的补充.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LinkedBear/spring-boot-source-analysis-code/2ec9ad6f307927458bc76c43524dc737bf116d52/q&a/36. 自动装配的补充.jpg
--------------------------------------------------------------------------------
/q&a/自动装配.md:
--------------------------------------------------------------------------------
1 | Q: `AutoConfigurationExcludeFilter` 这个过滤器会检测到 主启动类是一个配置类,然后就会不去扫描这个类了么?但是又为啥要过滤掉这些配置类呢?
2 | A:如果你在 SpringBoot 应用启动后打印一下IOC容器的所有Bean,会发现所有自动配置类都没有注册进去,这才是 `AutoConfigurationExcludeFilter` 的作用。至于过滤配置类的意图,这是 SpringBoot 的设计约定吧,自动配置类不应该是一个组件,就好比咱之前用 SpringFramework 时,用 xml 配置时,IOC容器也只是把 xml 里面定义的组件加载,而 xml 这个文件本身不在IOC容器中。
3 |
4 | Q:一个标注了 `@Configuration` 的类 本身是不应该被装载进IOC容器,但是其中的 `@Bean` 注解注入的bean会被装载进IOC容器的了,是这样吗?
5 | A:配置类的方式跟xml还是有区别的。配置类在IOC容器初始化时,需要被加载到IOC容器中才能被解析,这个事比较复杂,我简单概述下吧。IOC容器在初始化咱声明的组件也好,配置类也好,都是先将你配置的这些组件先封装为一个 `BeanDefinition`,之后再被一个叫 `ConfigurationClassPostProcessor` 的后置处理器解析(有关这个后置处理器的解释在第12篇的5.2章节),这个后置处理器会把咱写的配置类扫描到,再来解析配置类里头定义的@Bean等等。所以配置类要想里面的内容生效,需要先将配置类放入IOC容器,这样IOC容器里的特定组件(也就是 `ConfigurationClassPostProcessor`)才能对这些配置类进行处理。
6 |
7 | Q:这地方好像是因为需要同时满足 `@configuration` 和 `@AutoConfiguration` 两个注解才会去过来调。所以一般的 `@Configuration` 配置类还是会被包扫描到然后加入IOC容器中的了?
8 | A:没有 `@AutoConfiguration` 这个注解啊,它的判断依据是咱在小册里提到的 `spring.factories` 中配置的 `EnableAutoConfiguration` 的值
9 |
10 | -----------------------
11 |
12 | Q:`selectImports` 方法 `getAutoConfigurationEntry()` 中有一个 `fireAutoConfigurationImportEvents(configurations, exclusions);` 我看到在这之前对加载的配置进行了去重以及 exclude 以及使用了过滤器对一些配置类进行了排除,但是最后的这个 `fireAutoConfigurationImportEvents` 作用是什么?难道是有监听器在监听着自动配置?
13 |
14 | ```java
15 | private void fireAutoConfigurationImportEvents(List configurations, Set exclusions) {
16 | List listeners = getAutoConfigurationImportListeners();
17 | if (!listeners.isEmpty()) {
18 | AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, configurations, exclusions);
19 | for (AutoConfigurationImportListener listener : listeners) {
20 | invokeAwareMethods(listener);
21 | listener.onAutoConfigurationImportEvent(event);
22 | }
23 | }
24 | }
25 | ```
26 |
27 | A:自动配置完成后,`AutoConfigurationImportSelector` 会调你问题中提到的 `fireAutoConfigurationImportEvents` 方法,咱从源码中可以看到它会取一组类型为 `AutoConfigurationImportListener` 的监听器,执行它们的 `onAutoConfigurationImportEvent` 方法。借助IDEA查找这个接口的实现,发现只有一个实现类: `ConditionEvaluationReportAutoConfigurationImportListener`,这个名很长,咱从这个名上可以捕捉到一个概念:**report**。
28 |
29 | ```java
30 | /**
31 | * link AutoConfigurationImportListener to record results with the ConditionEvaluationReport.
32 | */
33 | class ConditionEvaluationReportAutoConfigurationImportListener
34 | implements AutoConfigurationImportListener, BeanFactoryAware {
35 | public void onAutoConfigurationImportEvent(AutoConfigurationImportEvent event) {
36 | if (this.beanFactory != null) {
37 | ConditionEvaluationReport report = ConditionEvaluationReport.get(this.beanFactory);
38 | report.recordEvaluationCandidates(event.getCandidateConfigurations());
39 | report.recordExclusions(event.getExclusions());
40 | }
41 | }
42 | // ......
43 | ```
44 |
45 | 其实在这个类的文档注释上写的很明白了,它的功能大概可以看出来是:记录条件装配的结果报告。如果你对此不是很了解,可以在 `application.properties` 中设置 `logging.level.root=debug`,在debug模式下,SpringBoot 会打印自动装配结果报告(这是 SpringBoot 基础知识)。
46 |
47 | 下面是Debug打印自动装配报告的节选:
48 |
49 | ```
50 | ValidationAutoConfiguration matched:
51 | - @ConditionalOnClass found required class 'javax.validation.executable.ExecutableValidator' (OnClassCondition)
52 | - @ConditionalOnResource found location classpath:META-INF/services/javax.validation.spi.ValidationProvider (OnResourceCondition)
53 |
54 | ValidationAutoConfiguration#defaultValidator matched:
55 | - @ConditionalOnMissingBean (types: javax.validation.Validator; SearchStrategy: all) did not find any beans (OnBeanCondition)
56 |
57 | ValidationAutoConfiguration#methodValidationPostProcessor matched:
58 | - @ConditionalOnMissingBean (types: org.springframework.validation.beanvalidation.MethodValidationPostProcessor; SearchStrategy: all) did not find any beans (OnBeanCondition)
59 |
60 | WebMvcAutoConfiguration matched:
61 | - @ConditionalOnClass found required classes 'javax.servlet.Servlet', 'org.springframework.web.servlet.DispatcherServlet', 'org.springframework.web.servlet.config.annotation.WebMvcConfigurer' (OnClassCondition)
62 | - found 'session' scope (OnWebApplicationCondition)
63 | - @ConditionalOnMissingBean (types: org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; SearchStrategy: all) did not find any beans (OnBeanCondition)
64 |
65 | WebMvcAutoConfiguration#formContentFilter matched:
66 | - @ConditionalOnProperty (spring.mvc.formcontent.filter.enabled) matched (OnPropertyCondition)
67 | - @ConditionalOnMissingBean (types: org.springframework.web.filter.FormContentFilter; SearchStrategy: all) did not find any beans (OnBeanCondition)
68 |
69 | WebMvcAutoConfiguration#hiddenHttpMethodFilter matched:
70 | - @ConditionalOnProperty (spring.mvc.hiddenmethod.filter.enabled) matched (OnPropertyCondition)
71 | - @ConditionalOnMissingBean (types: org.springframework.web.filter.HiddenHttpMethodFilter; SearchStrategy: all) did not find any beans (OnBeanCondition)
72 |
73 | ```
74 |
75 |
--------------------------------------------------------------------------------
/src/main/java/com/example/demo/DemoApplication.java:
--------------------------------------------------------------------------------
1 | package com.example.demo;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class DemoApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(DemoApplication.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/example/aop/DemoAspect.java:
--------------------------------------------------------------------------------
1 | package example.aop;
2 |
3 | import org.aspectj.lang.JoinPoint;
4 | import org.aspectj.lang.annotation.Aspect;
5 | import org.aspectj.lang.annotation.Before;
6 |
7 | @Aspect
8 | public class DemoAspect {
9 |
10 | @Before("execution(public * com.example.demo.*.*(..))")
11 | public void doBefore(JoinPoint joinPoint) {
12 | System.out.println("doBefore run...");
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/example/conditional/App.java:
--------------------------------------------------------------------------------
1 | package example.conditional;
2 |
3 | import org.springframework.context.annotation.AnnotationConfigApplicationContext;
4 |
5 | import java.util.stream.Stream;
6 |
7 | public class App {
8 |
9 | public static void main(String[] args) {
10 | AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ColorConfiguration.class);
11 | String[] beanDefinitionNames = ctx.getBeanDefinitionNames();
12 | Stream.of(beanDefinitionNames).forEach(System.out::println);
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/example/conditional/ColorConditional.java:
--------------------------------------------------------------------------------
1 | package example.conditional;
2 |
3 | import org.springframework.context.annotation.Condition;
4 | import org.springframework.context.annotation.ConditionContext;
5 | import org.springframework.core.type.AnnotatedTypeMetadata;
6 |
7 | public class ColorConditional implements Condition {
8 |
9 | @Override
10 | public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
11 | return context.getRegistry().containsBeanDefinition("red");
12 | }
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/example/conditional/ColorConfiguration.java:
--------------------------------------------------------------------------------
1 | package example.conditional;
2 |
3 | import example.enablexxx.Black;
4 | import example.enablexxx.Blue;
5 | import example.enablexxx.Red;
6 | import org.springframework.context.annotation.Bean;
7 | import org.springframework.context.annotation.Conditional;
8 | import org.springframework.context.annotation.Configuration;
9 |
10 | @Configuration
11 | public class ColorConfiguration {
12 |
13 | @Bean
14 | public Red red() {
15 | return new Red();
16 | }
17 |
18 | @Bean
19 | public Black black() {
20 | return new Black();
21 | }
22 |
23 | @Bean
24 | @Conditional(ColorConditional.class)
25 | public Blue blue() {
26 | return new Blue();
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/example/config/App.java:
--------------------------------------------------------------------------------
1 | package example.config;
2 |
3 | import org.springframework.context.annotation.AnnotationConfigApplicationContext;
4 |
5 | import java.util.stream.Stream;
6 |
7 | public class App {
8 |
9 | public static void main(String[] args) {
10 | AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigurationDemo.class);
11 | String[] beanDefinitionNames = ctx.getBeanDefinitionNames();
12 | Stream.of(beanDefinitionNames).forEach(System.out::println);
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/example/config/ConfigurationDemo.java:
--------------------------------------------------------------------------------
1 | package example.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.ComponentScan;
5 | import org.springframework.context.annotation.Configuration;
6 |
7 | import java.util.Date;
8 |
9 | @Configuration
10 | @ComponentScan("example.config")
11 | public class ConfigurationDemo {
12 |
13 | @Bean
14 | public Date currentDate() {
15 | return new Date();
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/example/customizer/WebMvcCustomizer.java:
--------------------------------------------------------------------------------
1 | package example.customizer;
2 |
3 | import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
4 | import org.springframework.boot.web.server.WebServerFactoryCustomizer;
5 | import org.springframework.core.Ordered;
6 | import org.springframework.core.annotation.Order;
7 | import org.springframework.stereotype.Component;
8 |
9 | @Order(0)
10 | @Component
11 | public class WebMvcCustomizer implements WebServerFactoryCustomizer, Ordered {
12 |
13 | @Override
14 | public void customize(TomcatServletWebServerFactory factory) {
15 | factory.setPort(9090);
16 | factory.setContextPath("/demo");
17 | }
18 |
19 | @Override
20 | public int getOrder() {
21 | return 0;
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/example/enablexxx/App.java:
--------------------------------------------------------------------------------
1 | package example.enablexxx;
2 |
3 | import org.springframework.context.annotation.AnnotationConfigApplicationContext;
4 |
5 | import java.util.stream.Stream;
6 |
7 | public class App {
8 |
9 | public static void main(String[] args) {
10 | AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ColorConfiguration.class);
11 | String[] beanDefinitionNames = ctx.getBeanDefinitionNames();
12 | Stream.of(beanDefinitionNames).forEach(System.out::println);
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/example/enablexxx/Black.java:
--------------------------------------------------------------------------------
1 | package example.enablexxx;
2 |
3 | public class Black {
4 |
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/example/enablexxx/Blue.java:
--------------------------------------------------------------------------------
1 | package example.enablexxx;
2 |
3 | public class Blue {
4 |
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/example/enablexxx/ColorConfiguration.java:
--------------------------------------------------------------------------------
1 | package example.enablexxx;
2 |
3 | import org.springframework.context.annotation.Configuration;
4 |
5 | @EnableColor
6 | @Configuration
7 | public class ColorConfiguration {
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/src/main/java/example/enablexxx/ColorImportBeanDefinitionRegistrar.java:
--------------------------------------------------------------------------------
1 | package example.enablexxx;
2 |
3 | import org.springframework.beans.factory.support.BeanDefinitionRegistry;
4 | import org.springframework.beans.factory.support.RootBeanDefinition;
5 | import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
6 | import org.springframework.core.type.AnnotationMetadata;
7 |
8 | public class ColorImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
9 |
10 | @Override
11 | public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
12 | registry.registerBeanDefinition("black", new RootBeanDefinition(Black.class));
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/example/enablexxx/ColorImportSelector.java:
--------------------------------------------------------------------------------
1 | package example.enablexxx;
2 |
3 | import org.springframework.context.annotation.ImportSelector;
4 | import org.springframework.core.type.AnnotationMetadata;
5 |
6 | public class ColorImportSelector implements ImportSelector {
7 |
8 | @Override
9 | public String[] selectImports(AnnotationMetadata importingClassMetadata) {
10 | return new String[] {Blue.class.getName(), Green.class.getName()};
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/example/enablexxx/ColorRegistrarConfiguration.java:
--------------------------------------------------------------------------------
1 | package example.enablexxx;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 |
6 | @Configuration
7 | public class ColorRegistrarConfiguration {
8 |
9 | @Bean
10 | public Yellow yellow() {
11 | return new Yellow();
12 | }
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/example/enablexxx/EnableColor.java:
--------------------------------------------------------------------------------
1 | package example.enablexxx;
2 |
3 | import org.springframework.context.annotation.Import;
4 |
5 | import java.lang.annotation.Documented;
6 | import java.lang.annotation.ElementType;
7 | import java.lang.annotation.Retention;
8 | import java.lang.annotation.RetentionPolicy;
9 | import java.lang.annotation.Target;
10 |
11 | @Documented
12 | @Retention(RetentionPolicy.RUNTIME)
13 | @Target(ElementType.TYPE)
14 | @Import({Red.class, ColorRegistrarConfiguration.class, ColorImportSelector.class, ColorImportBeanDefinitionRegistrar.class})
15 | public @interface EnableColor {
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/example/enablexxx/Green.java:
--------------------------------------------------------------------------------
1 | package example.enablexxx;
2 |
3 | public class Green {
4 |
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/example/enablexxx/Red.java:
--------------------------------------------------------------------------------
1 | package example.enablexxx;
2 |
3 | public class Red {
4 |
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/example/enablexxx/Yellow.java:
--------------------------------------------------------------------------------
1 | package example.enablexxx;
2 |
3 | public class Yellow {
4 |
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/example/init/Cat.java:
--------------------------------------------------------------------------------
1 | package example.init;
2 |
3 | import org.springframework.beans.factory.InitializingBean;
4 | import org.springframework.stereotype.Component;
5 |
6 | import javax.annotation.PostConstruct;
7 |
8 | @Component
9 | public class Cat implements InitializingBean {
10 |
11 | public Cat(String name) {
12 | System.out.println("Cat constructor run...");
13 | }
14 |
15 | @PostConstruct
16 | public void afterInit() {
17 | System.out.println("Cat PostConstruct run...");
18 | }
19 |
20 |
21 | @Override
22 | public void afterPropertiesSet() {
23 | System.out.println("Cat afterPropertiesSet run...");
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/example/init/CatBeanPostProcessor.java:
--------------------------------------------------------------------------------
1 | package example.init;
2 |
3 | import org.springframework.beans.BeansException;
4 | import org.springframework.beans.factory.config.BeanPostProcessor;
5 | import org.springframework.stereotype.Component;
6 |
7 | @Component
8 | public class CatBeanPostProcessor implements BeanPostProcessor {
9 |
10 | @Override
11 | public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
12 | if (bean instanceof Cat) {
13 | System.out.println("Cat postProcessBeforeInitialization run...");
14 | }
15 | return bean;
16 | }
17 |
18 | @Override
19 | public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
20 | if (bean instanceof Cat) {
21 | System.out.println("Cat postProcessAfterInitialization run...");
22 | }
23 | return bean;
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/example/servlet/DemoServlet.java:
--------------------------------------------------------------------------------
1 | package example.servlet;
2 |
3 | import javax.servlet.http.HttpServlet;
4 | import javax.servlet.http.HttpServletRequest;
5 | import javax.servlet.http.HttpServletResponse;
6 | import java.io.IOException;
7 |
8 | public class DemoServlet extends HttpServlet {
9 |
10 | @Override
11 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
12 | response.getWriter().println("demo servlet");
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/example/servlet/DemoServletRegistryBean.java:
--------------------------------------------------------------------------------
1 | package example.servlet;
2 |
3 | import org.springframework.boot.web.servlet.ServletRegistrationBean;
4 |
5 | public class DemoServletRegistryBean extends ServletRegistrationBean {
6 |
7 | public DemoServletRegistryBean(DemoServlet servlet, String... urlMappings) {
8 | super(servlet, urlMappings);
9 | }
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/example/servlet/ServletConfiguration.java:
--------------------------------------------------------------------------------
1 | package example.servlet;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 |
6 | @Configuration
7 | public class ServletConfiguration {
8 |
9 | @Bean
10 | public DemoServletRegistryBean demoServletRegistryBean() {
11 | return new DemoServletRegistryBean(new DemoServlet(), "/demo/servlet");
12 | }
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/example/transaction/service/DemoService.java:
--------------------------------------------------------------------------------
1 | package example.transaction.service;
2 |
3 | import org.springframework.stereotype.Service;
4 | import org.springframework.transaction.annotation.Propagation;
5 | import org.springframework.transaction.annotation.Transactional;
6 |
7 | @Service
8 | public class DemoService {
9 |
10 | @Transactional(rollbackFor = Exception.class, propagation = Propagation.NESTED)
11 | public void test1() {
12 | System.out.println("test1 run...");
13 | // int i = 1 / 0;
14 | System.out.println("test1 finish...");
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/example/transaction/service/DemoService2.java:
--------------------------------------------------------------------------------
1 | package example.transaction.service;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.stereotype.Service;
5 | import org.springframework.transaction.annotation.Propagation;
6 | import org.springframework.transaction.annotation.Transactional;
7 |
8 | @Service
9 | public class DemoService2 {
10 |
11 | @Autowired
12 | private DemoService demoService;
13 |
14 | @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
15 | public void test2() {
16 | System.out.println("test2 run...");
17 | demoService.test1();
18 | System.out.println("test2 finish...");
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------