零配置-@Import
@Import
注解就是代替XML里面的<import/>
标签,可以用于依赖第三方包中bean的配置和加载。
一、编写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.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import com.yiidian.dao.CustomerDao;
/**
* @author http://www.yiidian.com
*
*/
@Repository(value = "customerDao")
public class CustomerDaoImpl implements CustomerDao {
@Value("${jdbcUrl}")
private String jdbcUrl;
@Value("${driverClass}")
private String driverClass;
@Value("${user}")
private String user;
@Value("${password}")
private String password;
@Override
public String toString() {
return "CustomerDaoImpl [jdbcUrl=" + jdbcUrl + ", driverClass="
+ driverClass + ", user=" + user + ", password=" + password
+ "]";
}
@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;
import org.springframework.context.annotation.Import;
/**
* @author http://www.yiidian.com
*
*/
@Configuration
@ComponentScan(basePackages={"com.yiidian"})
@Import(JdbcConfig.class)
public class SpringConfig {
}
注意:SpringConfig类中用了@Import注解,目的是加载另一个配置类JdbcConfig,这样可以实现同时使用多个配置类(类似于XML方式的多个applicationContext.xml)
JdbcConfig配置类:
package com.yiidian.test;
import org.springframework.context.annotation.PropertySource;
@PropertySource(value="classpath:jdbc.properties")
public class JdbcConfig {
}
二、编写测试类
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");
System.out.println(customerDao);
}
}
三、运行结果
热门文章
优秀文章