纯注解快速使用spring IOC容器

时间:2023-03-08 22:33:38
纯注解快速使用spring IOC容器

使用spring的ioc容器实现对bean的管理与基本的依赖注入是再经典的应用了。基础使用不在详述。

这里主要介绍下使用注解实现零配置的spring容器。我相信你也会更喜欢使用这种方式。
Spring 3.0引入了JavaConfig,这种写法比xml文件的好处是具备类型安全检查.

1.定义一个简单的组件

package spring4;
import org.springframework.stereotype.Component;
/**
* Created by java技术.
*/ @Component
public class Compent {  
  public void show(){
     System.out.println("i am compent");
  }
}

2.定义配置信息类

package spring4;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* Created by java技术.
*/ @Configuration("name") //表示这是一个配置信息类,可以给这个配置类也起一个名称
@ComponentScan("spring4") //类似于xml中的<context:component-scan base-package="spring4"/>
public class Config {  
  @Autowired //自动注入,如果容器中有多个符合的bean时,需要进一步明确
  @Qualifier("compent") //进一步指明注入bean名称为compent的bean
  private Compent compent;
 
  @Autowired
  @Qualifier("newbean")    
  private Compent newbean;    
  @Bean //类似于xml中的<bean id="newbean" class="spring4.Compent"/>
  public Compent newbean(){        
    return new Compent();
  }    
  public void print(){
    System.out.println("i am beanname");
    ompent.show();
    newbean.show();
  }
}

3.启动spring容器

package spring4;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Created by java技术
*/ public class Application {    
  public static void main(String[] arg){        
//初始化spring容器,由于使用的是注解,没有xml文件,所有不再使用ClasspathXmlApplicationContext
    ApplicationContext context=new AnnotationConfigApplicationContext(Config.class);
    context.getBean("name",Config.class).print(); //配置类本身也是一个spring ioc容器中的bean,所以可以获取到它
  }
}

所有使用xml配置的信息都可以通过java类的方式配置。

混合使用多种配置方法

通常,可能在一个Spring项目中同时使用自动配置和显式配置,而且,即使你更喜欢JavaConfig,也有很多场景下更适合使用XML配置。幸运的是,这些配置方法可以混合使用。
首先明确一点:对于自动配置,它从整个容器上下文中查找合适的bean,无论这个bean是来自JavaConfig还是XML配置。
在JavaConfig中解析XML配置
通过@Import注解导入其他的JavaConfig,并且支持同时导入多个配置文件;
@Configuration
@Import({Config1.class, Config2.class})
public class SystemConfig {}

通过@ImportResource注解导入XML配置文件
@Configuration
@Import(Config1.class)
@ImportResource("classpath: config.xml")
public class SystemConfig {}

在XML配置文件中应用JavaConfig
通过<import>标签引入其他的XML配置文件;
通过<bean>标签导入Java配置文件到XML配置文件,例如<bean class="SystemConfig" />

事实上,基于xml的配置非常繁琐和笨重,注解已经成为事实上的主流。spring正是也注意到了这些,所以早已推出了支持注解的方式。spring体系中的boot项目更是为快速开发应用而生,零配置,一键启动web应用。作为开发者,我们更应该关注的是业务,不需要把时间花在对一些事实上会很少变更的形式的配置上。真正需要经常变更的也经常是业务上的配置,我们也会有相应的方案应对。

文章出处: