Spring 三种装配bean的方式

Spring有如下三种装配bean的方法

  • 在XML中进行显式配置
  • 在Java中进行显式配置
  • 隐式的bean发现机制和自动装配

显示配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--使用bean标签去申明bean-->
    <bean id="waiter" class="xyz.mrwood.study.spring.example.Waiter" />
    <!--可以保用p标签来注入依赖的bean-->
    <bean id="store" class="xyz.mrwood.study.spring.example.Store" p:waiter-ref="waiter" />

</beans>

在JAVA中显示配置

要通过@Configuration与@Bean搭配来完成

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeanConfig {

    /**
     * 申明bean
     * @return
     */
    @Bean
    public Waiter waiter() {

        return new Waiter();
    }

    @Bean
    public Store store() {

        Store store = new Store();
        store.setWaiter(waiter()); //通过调用bean的方法来注入
        return store;
    }
}

隐式配置

@Component:标识Bean,可被自动扫描发现

@Configuration+ @ComponentScan(basepackages=”main”) : @Configuration可以指定某个类为配置类,而@ComponentScan可以指定要扫描组件的范围,不设置参数默认扫描当前类的包以及子包。如果设置会扫描指定的类。

上述也可以换成XML配置指定扫描的包路径

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="*.*.*" />

</beans>

 @Autowired:自动装配,查找容器中满足条件的Bean,注入。

总结:

1、spring中所有bean都会有一个ID,我们通过@Component设置的,自动扫描时会以类名首字母小写为ID。如果想要自定义就要设置@Component的参数
2、@ComponentScan默认是扫描当前包以及子包。如果想设置其它包或者多个包,可以通过设置该注解的basePackages。但是这种是以字符串形式不利于重构。可以使用另外一个属性backPackageClasses指定某个类(开发中常用标记接口),然后spring会扫描这个类下面的包与子包。
3、可以使用java规范的@Named替换@Component,也可以使用java规范的@Inject去替换@Autowired
4、@Bean注解的bean的ID默认是方法名,如果要指定名称,可以通过name属性来设置

猜你喜欢

转载自blog.csdn.net/jzg5845201314/article/details/84973227