Spring框架使用纯注解的方式来配置IOC

来源:互联网 发布:淘宝上比较好的手办店 编辑:程序博客网 时间:2024/04/25 14:40

使用纯注解的方式来配置IOC

只需要将applicationContext.xml配置文件文件替换成一个配置类即可。

 

1.  创建一个配置类来替换xml配置文件。

使用@Configuration注解来指定Spring配置类。当创建容器时会从该类上加载注解。

使用@ComponenScan注解来指定初始化容器时要扫描的包。

属性:

    basePackages:用于指定要扫描的包。和该注解中的value属性作用一样。 值是一个字符串的数组

@ComponentScan(basePackages={"com.itheima","cn.itcast"})

和xml配置文件中开启扫描注解的作用一样。

<context:component-scanbase-package="com.itheima"/>

 

2. 使用@Import注解可以导入其他配置类。

Value[]属性:指定其他配置类的字节码文件对象。(是一个数组)

@Import({ config_B.class})//引入config_B配置类。

 

 

那么新的问题又来了,我们如何获取容器呢?

//1.获取容器:由于我们已经没有了xml文件,所以再用读取xml方式就不能用了。

//这时需要指定加载哪个类上的注解

ApplicationContextac = new  AnnotationConfigApplicationContext(SpringConfig.class);

        //2.根据id获取对象

    CustomerService cs = (CustomerService)ac.getBean("customerService");

 

直接上代码演示

 

持久层代码

@Repository(value="customerDao")

public class CustomerDaoImpl implements CustomerDao{

 

    @Override

    public void save() {

       // TODO Auto-generated method stub

       System.out.println("--持久层..");

    }

 

}

业务层代码

@Service(value="customerService")

class CustomerServiceImplimplements CustomerService {

 

    @Resource(name="customerDao")

    private CustomerDaocustomerDao;

   

    public void save() {

       customerDao.save();

       System.out.println("-业务层..");

    }

 

}

测试类代码

/**

 * 使用纯注解方式配置IOC

 */

public class Demo_Anno {

    @Test

    public void   fun() {

       //获取容器 与加载xml配置文件的不一样,这是加载配置类

       ApplicationContext ac =newAnnotationConfigApplicationContext(SpringConfig.class);

       //根据id获取对象

       CustomerService cs =(CustomerService)ac.getBean("customerService");

       cs.save();

      

    }

}

配置类代码

/*

 * 配置类

 */

@Configuration      //指明当前类是配置类

@ComponentScan(basePackages={"com.itheima","cn.itcast"})//指定初始化容器时要扫描的包

public class SpringConfig {

   

}

原创粉丝点击