Spring学习(二) ---- 纯注解开发模式
1、配置管理第三方Bean
下面通过对Druid数据库连接池进行配置进行演示
导入jar包
准备properties文件
编写数据库的xml文件,使用jdbcTemplate来管理
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1.加载外部的properties文件 system-properties-mode:不加载系统的properties文件模板,不会出现冲突情况 -->
<context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="NEVER"/>
<!-- 2.配置连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driveClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="initialSize" value="${jdbc.initialSize}"/>
<property name="maxActive" value="${jdbc.maxActive}"/>
</bean>
<!-- 3.配置Spring封装的JDBC JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
在ApplicationContext.xml中引入配置文件
<import resource="applicationContext-dao.xml"/>
2、纯注解开发模式
前面已经可以使用注解来配置bean,但是依然有用到配置文件,在配置文件中对包进行了扫描,
Spring在3.0版已经支持纯注解开发
Spring3.0开启了纯注解开发模式,使用Java类替代配置文件,开启了Spring快速开发
2.1 实现步骤:
1、创建配置类
//表明这是一个配置类 相当于替换了applicationContext.xml
@Configuration
//添加包扫描注解 @ComponentScan替换 <context:component-scan base-package=""/>
@ComponentScan("com.gxa")
public class SpringConfig {
}
2、测试运行
import com.gxa.bean.CVN;
import com.gxa.config.SpringConfig;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestSpring2 {
@Test
public void testHello(){
//1.创建容器 使用AnnotationConfigApplicationContext -- 注解配置的ioc容器
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
//2.从容器中获取bean对象
CVN cvn = applicationContext.getBean(CVN.class);
System.out.println(cvn);
}
}
重点:
@Configuration注解
@ComponentScan注解
2.2 其他注解复习
@Scope注解
@PostConstruct//配置初始化的方法
@PreDestroy//配置销毁的方法
2.3 读取propertier配置文件的注解
在SpringConfig配置文件中配置@PropertySource标签
@Configuration
@ComponentScan("com.gxa")
@PropertySource("jdbc.properties")
public class SpringConfig {
}
读取文件中的值,使用这个@Value("${ }")注解 读取 properties中的参数
@Repository("bookDao")
public class BookDaoImpl implements BookDao {
@Value("${name}")
private String name;
public void save() {
System.out.println("book dao save ..." + name);
}
}