spring中xml配置和类配置
基于xml进行配置的方式初始化容器,ClasspathXmlApplicationContext,这种方式在ssm整合时候使用。
基于类进行配置的方式来初始化容器:AnnocationConfigApplicationContext,这种方式在springboot框架使用。
基于 xml 的 spring 文件配置
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启包扫描注解-->
<context:component-scan base-package="com.hang"/>
<!--导入jdbc.properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置druid数据库连接池-->
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="initialSize" value="${jdbc.initialSize}"/>
</bean>
<!--开启aop注解-->
<aop:aspectj-autoproxy/>
</beans>
spring 的类配置方式(和xml配置文件做对比进行配置)
@Configuration // 表示当前类是一个配置类,此对象也会注册进入容器
// IOC,di注解识别和xml配置文件中的<context:component-scan base-package="com.hang"/>一致
@ComponentScan(basePackages = "com.hang")
@PropertySource("classpath:jdbc.properties") // 加载外部properties文件
@EnableAspectJAutoProxy //开启aop注解识别
@Import(DaoConfig.class) //导入其他类配置文件
public class AppConfig {
@Value("${jdbc.url}") // 在bean中获取容器中的properties数据
String url;
@Value("${jdbc.driver}")
String driver;
@Value("${jdbc.username}")
String username;
@Value("${jdbc.password}")
String password;
@Value("${jdbc.initialSize}")
Integer initialSize;
// 注册非自定义对象进入spring容器中 把方法的返回值注册容器,方法名作为bean的id
@Bean(initMethod = "init",destroyMethod = "close")
public DruidDataSource druidDataSource(){
DruidDataSource ds = new DruidDataSource();
ds.setUsername(username);
ds.setUrl(url);
ds.setDriverClassName(driver);
ds.setPassword(password);
ds.setInitialSize(initialSize);
return ds;
}
// 调用方法时,先按照方法的形参名获取bean,再按照类型获取
@Bean
public MyTransactionManager myTransactionManager(DruidDataSource druidDataSource){
// 在MyTransactionManager内部,需要DruidDataSource对象,调用set方法注入
MyTransactionManager tm = new MyTransactionManager();
tm.setDataSource(druidDataSource);
return tm;
}
}