Sprng 往IOC容器中添加组件的几种方式,可能你只知道第一种

通过@ComponentScan @Controller @Service @Respository @Component

① @ComponentScan

相当于XML中配置的

<code><component-scan>。/<component-scan>/<code>

使用方法如下,

<code>@ComponentScan(value = "com.yj.controller")
public class BeanConfig {

}/<code>

在 @ComponentScan 注解中指定了要扫描的包。

Spring 会扫描 com.yj.controller 下的所有类。

使用场景: 针对我们自己写的组件可以通过该方式来进行加载到容器中

② @Controller

用于标注控制层,相当于SpringMvc 中的 控制层

③ @Service

用于标注服务层,主要用来进行业务的逻辑处理

④ @Respository

用于标注数据访问层,也可以说用于标注数据访问组件,即DAO组件.

泛指组件,当组件不好归类的时候,我们可以使用这个注解

通过@Bean的方式来导入组件(实用于导入第三方组件的类)


比如:

<code>
@Configuration
public class MyAppConfig {
    //将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
    @Bean
    public HelloService helloService02(){
        System.out.println("配置类@Bean给容器中添加组件了...");
        return new HelloService();
    }
}/<code>


1、配置类@Configuration------>Spring配置文件

2、使用@Bean给容器中添加组件,相当于XML中共的<bean> 标签


通过@Import来导入 组件(导入组件的id为全类名路径)


<code>@Configuration
//@Import(value = {Person.class, Car.class})
//@Import(value = {Person.class, Car.class, YjImportSelector.class})
@Import(value = {Person.class, Car.class, YjImportSelector.class, YjBeanDefinitionRegister.class})
public class MainConfig {
}/<code>

通过@Import 的ImportSeletor类实现组件的导入 (导入组件的id为全类名路径)

<code>public class YjImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{"com.yj.testimport.compent.Dog"};
}
}/<code>

通过@Import的 ImportBeanDefinitionRegister导入组件 (可以指定bean的名称)


<code>public class YjBeanDefinitionRegister implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Cat.class);
registry.registerBeanDefinition("cat",rootBeanDefinition);
}
}/<code>

通过实现FactoryBean接口来实现注册组件


Spring 通过反射机制利用<bean>标签的class 属性来实例化beande , 在有些情况下,实例化Bean的方式比较复杂,则需要在bean标签中提供大量的配置信息。/<bean>

这时偶尔们可以通过实现Spring提供的一个FactoryBean接口,用户可以通过实现该接口定义实例化 Bean的逻辑。

比如我们定义一个生产 Car 的 工厂bean

<code>public class CarFactoryBean implements FactoryBean {
   
    /返回bean的对象
    @Override

    public Car getObject() throws Exception {
        return new Car();
    }
   
    /返回bean的类型
    @Override
    public Class> getObjectType() {
        return Car.class;
    }
   
    /是否为单利
    @Override
    public boolean isSingleton() {
        return true;
    }
}
/<code>


<code>
<beans> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean>

<bean>
<property>
/<bean>

/<beans>/<code>


<code>@Configuration
@ImportResource(locations = {"classpath:beans.xml"})
public class MainConfig {
@Bean
public CarFactoryBean carFactoryBean() {
return new CarFactoryBean();
}
}
/<code>


分享到:


相關文章: