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>
上一篇:HDU - 3980 Paint Chain(SG函数)


下一篇:Leetcode Spiral Matrix II