Java编程配置优点:相对于xml配置而言,其结构更清晰,可读性更高,同时也节省了解析xml耗时。
Java编程配置缺点:修改应用配置参数需要重新编译。其实并不是一个大的问题,实际生成环境中,应用配置完成后一般都不会也不敢去随意修改。
两者各有千秋,考虑到Spring4.x和SpringBoot都在推荐使用Java编程配置的方式,那我们也应该顺应时代潮流,你可以不用,但你应该要懂!
Java编程配置步骤
第一步:创建配置类,在类名上添加注解Configuration,告知Spring这是一个配置类,其作用类似xml文件
第二步:加载外部配置文件,在类名上添加注解PropertySource,指定properties文件的读取路径
第三步:获取应用配置属性值,在属性变量上添加注解Value,通过${}表达式获取配置文件中参数
第四步:依赖注入,在方法上添加Bean注解,也可以用FactoryBean
第一步和第四步的语法,文章第二部分会详细介绍。第二步和第三步的语法,文章第三部分会详细介绍。
`import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/** * Spring 配置类 * 配置数据源,事务管理,bean,自动扫描包 * @author itdragon */
@Configuration // 声明该类为配置类
@PropertySource({"classpath:propertySource.properties"}) // 引入外部文件
@ComponentScan("com.itdragon") // 配置自动扫描包的路径
@EnableTransactionManagement // 开启基于注解的事务管理功能
public class ApplicationContextConfig {
@Value("${DATA_USER}")
private String DATA_USER;
@Value("${DATA_PAWD}")
private String DATA_PAWD;
@Value("