springboot--bean交給容器


1、把bean交給springboot管理

  springboot也是一個spring容器。把一個bean交給springboot的容器有三種方法,前兩種是先把bean交給spring容器再把spring容器交給springboot容器,第三種是直接交給springboot容器。

1.1 @ImportResource

  在resources下像往常一樣編寫xml配置文件,在springboot啟動類加上@importResource注解並在value數組里指明配置文件的位置,即可把spring容器和springboot容器整合一起。

1.2 @Configuration

  上一種方法的弊端是如果存在多個xml配置文件則需要在@ImportResource中引入多個注解。所以springboot推薦使用基於@Configuration注解的形式去替代xml文件來向spring容器添加bean。

  從Spring3.0起@Configuration開始逐漸用來替代傳統的xml配置文件。@Configuration繼承自@Component,spring會把標注了@Configuration的對象管理到容器中。除此之外還要在某一個方法加上@Bean,該方法的返回對象被當做bean交給容器,該bean的名稱為方法的名稱。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}
@Configuration
public class myAppConfig {

    @Bean
    public helloService helloService(){
        System.out.println("給容器添加組件");
        helloService helloService = new helloService();
        return helloService;
    }
}

  執行下列測試,控制台有相應的輸出,並得到了helloService。

    @Autowired
    ApplicationContext applicationContext;

    @Test
    public void test(){
        helloService bean = applicationContext.getBean("helloService",helloService.class);
        System.out.println(bean);
    }

1.3 大雜燴

  這種方式和傳統的基於注解spring注入bean相同,在pojo類上使用@Component把該pojo對象交給spring容器,並使用注解如@Value為pojo對象的屬性添加值,只不過在添加值方面springboot有些不同。

  把person對象交給容器管理並為之設置初始值。

public class Person {
    private String  lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;

    private Map<String,Object> maps;
    private List<String> lists;

    private Pet pet;
}

public class Pet {
    private String  name;
    private Integer age;
}

   首先要編寫XX.propertites配置文件為相關屬性指定值。

person.age=10
person.birth=1029/1/1
person.boss=false
person.last-name=wuwuwu
person.maps.k1=v1
person.maps.k2=v2
person.lists=l1,l2
person.pet.age=10
person.pet.name=gou

   然后在Person上加上注解,告訴properties文件的位置和使用具體的前綴。springboot有一個默認的配置文件application.properties,如果默認配置文件中和自定義的配置文件有重合的部分,則默認配置文件會覆蓋自定義配置文件。

@Component
@PropertySource(value = {"classpath:Person.properties"})
@ConfigurationProperties(prefix = "person")

  除此之外可使用一個插件提高編寫properties的效率。

        <!--方便編寫配置文件的插件-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM