2021-05-03 09:46  阅读(130)
文章分类:Spring 入门教程 文章标签:SpringSpring 教程
©  原文作者:一点教程 原文地址:http://www.yiidian.com/spring/

@ComponentScan注解代替XML配置方式的<context:component-scan/>标签的作用。用于开启SpringIOC的注解扫描。

一、编写Bean类

CustomerDao接口:

    
    package com.yiidian.dao;
    /**
     * 
     * @author http://www.yiidian.com
     *
     */
    public interface CustomerDao {
    	public void save();
    }
    

CustomerDaoImpl实现:

    
    package com.yiidian.dao.impl;
    
    import org.springframework.stereotype.Repository;
    
    import com.yiidian.dao.CustomerDao;
    /**
     * @author http://www.yiidian.com
     *
     */
    @Repository(value="customerDao")
    public class CustomerDaoImpl implements CustomerDao {
    
    	@Override
    	public void save() {
    		System.out.println("执行了CustomerDaoImpl的save()方法");
    	}
    	
    }
    

SpringConfig启动类(重点在这里):

    
    package com.yiidian.test;
    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * @author http://www.yiidian.com
     *
     */
    @Configuration
    @ComponentScan(basePackages={"com.yiidian"}) //basePackages:可以放置一个或多个包扫描范围
    public class SpringConfig {
    }

二、编写测试类

    
    package com.yiidian.test;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    import com.yiidian.dao.CustomerDao;
    
    public class Demo1 {
    	@Test
    	public void test1(){
    		ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
    		CustomerDao customerDao = (CustomerDao)ac.getBean("customerDao");
    		customerDao.save();
    	}
    }
    

三、运行结果

2021050309460240111_1.png

源码下载:http://pan.baidu.com/s/1nuRngb3

点赞(0)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> 零配置-@ComponentScan
上一篇
零配置-@Configuration
下一篇
零配置-@PropertySource