1.maven中导入相关的依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.3</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
</dependencies>
2.创建核心配置类代替(applicationContet.xml)
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* 使用spring新注解定义一个spring配置文件总类 代替spring的xml文件
*/
@Configuration //标记该类是spring的核心配置类
@ComponentScan("要扫的包名") //开启扫包使用注解开发bean
@Import({SpringDataSourceConfiguration.class})// 加载引入配置分类
public class SpringConfiguration {
}
3.创建核心配置类的分类-配置数据源(这里用的c3p0)
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
/**
* 定义spring配置文件类的 分类
*/
@PropertySource("classpath:jdbc.properties") //加载连接数据库的配置文件
public class SpringDataSourceConfiguration {
//将注入ioc容器中的数据库的配置文件中的值注入到对应的属性中
@Value("${jdbc.driver}")
private String drive;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String userName;
@Value("${jdbc.password}")
private String password;
//将获取到的数据库配置文件的值设置到数据库连接池中 返回数据源 这里使用的是c3p0数据库连接池
@Bean("dataSource") // spring会将当前方法的返回值以 指定名称返回到ioc容器中
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(drive);
dataSource.setJdbcUrl(url);
dataSource.setUser(userName);
dataSource.setPassword(password);
return dataSource;
}
}
4.编写Dao层与service层
package com.heima.dao;
import org.springframework.stereotype.Repository;
@Repository("testDao")
public class TestDaoImpl implements TestDao {
@Override
public void run() {
System.out.println("目标方法被运行》》》》》》》》》》");
}
}
-----------------------------------------------------------------------------------
import com.heima.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service("testService")
public class TestServiceImpl implements TestService {
@Autowired
@Qualifier("testDao")
private TestDao testDao;
@Override
public void testRun() {
testDao.run();
}
}
5.编写测试类加载spring的核心配置类,获取到service层的bean调用测试方法
@Test
public void test01(){
//加载spring核心配置类
ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
TestService service = app.getBean(TestService.class);
service.testRun();
}