注解式编程

注解式编程

  • 创建maven工程并导包
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.12.RELEASE</version>
</dependency>

① 配置类&Bean注解

/**
 * @Configuration: Spring的配置标签,打在类上,该类就可以被识别为Spring的配置类
 * 该配置类相当于  applicationContext.xml
 */
@Configuration
public class ApplicationConfig {
    /**
     * @Bean :Spring的Bean定义标签,打在方法上,方法返回的实例自动回交给Spring容器管理
     * 相当于  <bean id="myBean"/>
     * @return
     */
    @Bean
    public MyBean myBean(){
        MyBean myBean = new MyBean();
        return myBean;
    }
}

② @ComponentScan扫描bean

/**
 * @Configuration: Spring的配置标签,打在类上,该类就可以被识别为Spring的配置类
 * 该配置类相当于  applicationContext.xml
 *
 * @ComponentScan : 开启IOC组件自动扫描(@Component,@Repository,@Service,@Controller) ,
 * 该标签默认扫描当前包及其子包 ,当然也可以使用 basePackages指定扫描的包路径
 *
 * @ComponentScan(basePackages = "cn.xx.spring._03scan")扫描此包
 * @ComponentScan (不写里面的值)默认扫描当前包
 */
@Configuration
@ComponentScan
public class ApplicationConfig {
}
//定义bean 交给spring管理
@Component
public class MyBean {
}

③ @Scope组件范围&@Lazy懒加载-认识

@Configuration
public class ApplicationConfig {
    /**
     *  bean的id : 就是方法的名字
     *  bean的name: 可通过@Bean.name属性指定
     *  lazy-init :通过标签指定 @Lazy 标签指定
     *  bean的scope : @Scope("prototype") 标签指定(单例,多例)
     * @return
     */
    @Bean(name = "myBean2",initMethod = "init",destroyMethod = "destory")
//    @Lazy
//    @Scope("prototype")
    public MyBean myBean(){
        MyBean myBean = new MyBean();
        return myBean;
    }
}

④ @Conditional-按照条件注册

  • ApplicationConfig:
@Configuration
public class ApplicationConfig {
    //定义windowBean :条件 ,根据系统环境指定定义的bean
    @Bean
    @Conditional(value = WindowBeanCreateCondition.class)
    public MyBean windowsBean(){
        MyBean myBean = new MyBean();
        myBean.setSystem("windows");
        return myBean;
    }

    //定义linuxBean
    @Bean
    @Conditional(value = LinuxBeanCreateCondition.class)
    public MyBean linuxBean(){
        MyBean myBean = new MyBean();
        myBean.setSystem("linux");
        return myBean;
    }
}
  • LinuxBeanCreateCondition:
/**
 * bean创建条件,根据系统环境(windows ,linux)决定创建windowBean或者linuxBean
 * @param context conditionContext条件上下文,可以获取一些信息,来判断是否条件
 * @param annotatedTypeMetadata 当前方法或注解类的注解类型元数据信息
 */
public class LinuxBeanCreateCondition implements Condition {
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //获取操作系统名字
        Environment environment = context.getEnvironment();
        String systemName = environment.getProperty("os.name");
        if(systemName.contains("linux")){
            return true;
        }
        return false;
    }
}
  • WindowsBeanCreateCondition:
/**
 * bean创建条件,根据系统环境(windows ,linux)决定创建windowBean或者linuxBean
 */
public class WindowBeanCreateCondition implements Condition{

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        //获取操作系统名字
        Environment environment = conditionContext.getEnvironment();
        String systemName = environment.getProperty("os.name");
        if (systemName.toUpperCase().contains("WINDOWS")){
            return true;
        }
        return false;
    }
}

⑤ @Import

  • 方式一:import_config通过类进行导入
@Configuration
@Import({ApplicationOtherConfig.class,TempBean.class})
public class ApplicationConfig {

    @Autowired
    private OtherBean otherBean;

    //定义linuxBean
    @Bean
    public MyBean myBean(){
        MyBean myBean = new MyBean();
        myBean.setOtherBean(otherBean);
        return myBean;
    }
}
==============================================
public class ApplicationOtherConfig {
    @Bean
    public OtherBean otherBean(){
        return new OtherBean();
    }
}
==============================================
public class TempBean {
}
==============================================
public class MyBean {
    private OtherBean otherBean;

    public OtherBean getOtherBean() {
        return otherBean;
    }

    public void setOtherBean(OtherBean otherBean) {
        this.otherBean = otherBean;
    }
}
  • 方式二:ImportSelector通过选择器导入
@Configuration
//根据选择器返回的类的全限定名来导入类
@Import(MyImportSelector.class)
public class ApplicationConfig {
}
===========================================
//自定义导入选择器 ,通过@Import标签导入
public class MyImportSelector implements ImportSelector{
    //方法返回要交给Spring容器管理的类的全限定名
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        return new String[]{
                "cn.hx.spring._08import_selector.MyBean",
                "cn.hx.spring._08import_selector.OtherBean"
        };
    }
}
===========================================
public class OtherBean {
}
===========================================
public class MyBean {
}
  • 方式三:ImportBeanDefinitionRegistrar通过注册器导入
@Configuration
@Import(MyImportBeanDefinitionRegistrar .class)
public class ApplicationConfig {
}
===========================================
//bean的注册器
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    //通过BeanDefinitionRegistry来注册bean
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        registry.registerBeanDefinition("myBean",new RootBeanDefinition(MyBean.class));
        registry.registerBeanDefinition("otherBean",new RootBeanDefinition(OtherBean.class));
    }
}
===========================================
public class OtherBean {
}
===========================================
public class MyBean {
}

⑥ 用FactoryBean注册组件

public class MyBeanFactoryBean implements FactoryBean<MyBean>{
    @Override
    public MyBean getObject() throws Exception {
        //返回真实的bean的实例
        return new MyBean();
    }

    @Override
    public Class<?> getObjectType() {
        //返回真实的bean的类型
        return MyBean.class;
    }

    @Override
    public boolean isSingleton() {
        //是否单例
        return true;
    }
}
===========================================
@Configuration
public class ApplicationConfig {
    @Bean
    public MyBeanFactoryBean myBean(){
        return new MyBeanFactoryBean();
    }
}
===========================================
public class MyBean {
}

⑦组件生命周期

  • 方式一、@Bean
@Scope("prototype")
@Bean(initMethod = "init",destroyMethod = "destory")
public Car car()
{
    return new Car();
}
===========================================
@Test
public void test01(){
	AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(MainConfigLifeCycle.class);
    //第一次调用
    context.getBean("car");
    //单实例bean关闭容器时销毁,多实例对象不销毁
    context.close();
}
  • 方式二、接口InitializingBean和DisposableBean
public class MyBean implements InitializingBean,DisposableBean{
    @Override
    public void destroy() throws Exception {
        System.out.println("销毁了");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("被初始化了");
    }
}
===========================================
@Configuration
public class ApplicationConfig {
    @Bean
    public MyBean myBean(){
        return new MyBean();
    }
}
  • 方式三、注解@PostConstruct @PreDestroy
public class MyBean {
    @PreDestroy
    public void destroy() throws Exception {
        System.out.println("销毁了");
    }
    @PostConstruct
    public void afterPropertiesSet() throws Exception {
        System.out.println("被初始化了");
    }
}
===========================================
@Configuration
public class ApplicationConfig {
    @Bean
    public MyBean myBean(){
        return new MyBean();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值