零配置-@ComponentScan

@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();
	}
}

三、运行结果

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

热门文章

优秀文章