Browse Source

添加文章 spring boot bean 创建

王智勇 5 years ago
parent
commit
68d61e7638
1 changed files with 66 additions and 0 deletions
  1. 66 0
      source/_posts/SpringbootBean.md

+ 66 - 0
source/_posts/SpringbootBean.md

@@ -0,0 +1,66 @@
+---
+title: Springboot Bean 小记
+date: 2018-10-25 10:01:17
+tags: [Spring Boot,Bean]
+categories: [Java,Spring]
+---
+### Spring boot 中创建bean的方式
+
+- @Component Spring中最广的注解
+```java
+@Compent
+public class DemoBean(){
+
+}
+```
+
+- @Bean 一般使用在动态代理的配置类中 @Configuration
+```java
+Configuration
+public class DemoConfig(){
+    
+    private DemoClass demoClass;
+
+    @Bean
+    public DemoClass demoClass(){
+        return demoClass;
+    }
+}
+```
+
+顺便说下两个注解的区别
+> 在Component中(@Component标注的类,包括@Service,@Repository, @Controller)使用@Bean注解和在@Configuration中使用是不同的。在@Component类中使用方法或字段时不会使用CGLIB增强(及不使用代理类:调用任何方法,使用任何变量,拿到的是原始对象)。而在@Configuration类中使用方法或字段时则使用CGLIB创造协作对象(及使用代理:拿到的是代理对象);当调用@Bean注解的方法时它不是普通的Java语义,而是从容器中拿到由Spring生命周期管理、被Spring代理甚至依赖于其他Bean的对象引用。在@Component中调用@Bean注解的方法和字段则是普通的Java语义,不经过CGLIB处理
+
+简单来说就是 @Configuration 里面多处理了一层,动态增强了,例如同一个bean 就不会被重复生成,而 @Component 就会
+
+### 统一封装springboot dubbo 的调用 封装到一个类中
+```java
+@Configuration
+public class DubboApiBean {
+
+    @Reference(version = "1.0")
+    private IPersonnelApi personnelApi;
+
+    @Reference(version = "1.0")
+    private IPrivilegeApi privilegeApi;
+
+    @Reference(version = "1.0")
+    private IMisApi misApi;
+
+    @Bean
+    public IPersonnelApi personnelApi() {
+        return personnelApi;
+    }
+
+    @Bean
+    public IPrivilegeApi privilegeApi() {
+        return privilegeApi;
+    }
+
+    @Bean
+    public IMisApi misApi(){
+        return misApi;
+    }
+}
+```
+在调用时直接使用@Resource 或@Autowired