Spring
IOC
配置方式实现
<?xml version="1.0" encoding="UTF-8"?>
<!--在使用spring 相关jar包的时候进行配置 每个jar包对应一个xmlns和schemaLocation路径-->
<!--格式基本相关 只要修改相关的关键字-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx = "http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 开启注解扫描 ,才可以使用注解 可以使用use-default-filter配合include-filer和exclude-filter使用 -->
<context:component-scan base-package="com.jdbcTemplate" ></context:component-scan>
<!-- 引入外部属性文件,以配置连接池为例-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${prop.driverClass}"></property>
<property name="url" value="${prop.url}"></property>
<property name="username" value="${prop.userName}"></property>
<property name="password" value="${prop.password}"></property>
</bean>
<bean id="order" class="com.ioc.example.Order">
<!-- <constructor-arg />表示构造器方法注入-->
<constructor-arg name="oname" value="Lucy"/>
<constructor-arg name="address" value="ShangHai"/>
<!-- <property />表示用set方法注入属性-->
</bean>
注解方式实现:
Bean 管理中创建对象注解:
(1)@Component 一般Bean
(2)@Service 业务层
(3)@Controller 表现层
(4)@Repository 持久层
属性注入:
@Autowired:属性自动装配
@Qialifier 名称注入 需要和Autowired一起使用
@Value:注入普通类型属性
完全注解开发(即创建配置类代替xml文件):
@Configuration //作为配置类,替代 xml 配置文件
@ComponentScan(basePackages = {"com.example"})
public class SpringConfig {
}
AOP
配置方式实现
<!-- 1、创建两个类,增强类和被增强类,创建方法-->
<!-- 2、在 spring 配置文件中创建两个类对象-->
<!--创建对象-->
<bean id="book" class="com.aop.User"></bean>
<bean id="bookProxy" class="com.aop.UserProxy"></bean>
<!-- 3、在 spring 配置文件中配置切入点-->
<!--配置 aop 增强--> <aop:config>
<!--切入点-->
<aop:pointcut id="p" expression="execution(*
com.aop.User.buy(..))"/>
<!--配置切面-->
<aop:aspect ref="bookProxy">
<!--增强作用在具体的方法上-->
<aop:before method="before" pointcut-ref="p"/>
</aop:aspect>
注解方式实现
步骤:
- 在 spring 配置文件中,开启注解扫描
- 使用注解创建 User 和 UserProxy 对象
- 在增强类上面添加注解 @Aspect
@Component
@Aspect //生成代理对象
public class UserProxy {
- 在 spring 配置文件中开启生成代理对象
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
- List item配置不同类型的通知@Before @AfterReturning @After @AfterThrowing @Around
对于相同的切入点,可以抽取出来
5、相同的切入点抽取
//相同切入点抽取
@Pointcut(value = "execution(* com.example.aopanno.User.add(..))")
有无异常都执行
只是后置通知
就是对相同的切入点进行抽取出来,写一个空的方法上
public void pointdemo() {
}
//前置通知
//@Before 注解表示作为前置通知
@Before(value = "pointdemo()")
public void before() {
System.out.println("before.........");
}
完全注解实现
@Configuration
@ComponentScan(basePackages = {"com.example})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAop {
}
JdbcTemplate
配置xml内容
<!-- 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="jdbc:mysql:///user_db" />
<property name="username" value="root" />
<property name="password" value="root" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
</bean> (
配置 JdbcTemplate 对象,注入 DataSource
<!-- JdbcTemplate 对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入 dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
创建 service 类,创建 dao 类,在 dao 注入 jdbcTemplate 对象
数据库操作的增查改
修改 增加 删除 都使用update 区别只在于sql语句不同
@Override
public void updateBook(Book book) {
String sql = "update t_book set username=?,ustatus=? where user_id=?";
Object[] args = {book.getUsername(), book.getUstatus(),book.getUserId()};
int update = jdbcTemplate.update(sql, args);
System.out.println(update);
}
查找返回某个值,使用queryForObject
@Override
public int selectCount() {
String sql = "select count(*) from t_book";
Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
return count;
}
查找返回对象和对象集合使用queryForObject
⚫ 有三个参数
第一个参数:sql 语句 第二个参数:RowMapper 是接口,针对返回不同类型数据,使用这个接口里面实现类完成
数据封装
第三个参数:sql 语句值填充
//查询返回对象
@Override
public Book findBookInfo(String id) {
String sql = "select * from t_book where user_id=?";
//调用方法
Book book = jdbcTemplate.queryForObject(sql, new
BeanPropertyRowMapper<Book>(Book.class), id);
return book;
}
//查询返回集合 只有两个参数
@Override
public List<Book> findAllBook() {
String sql = "select * from t_book";
//调用方法
List<Book> bookList = jdbcTemplate.query(sql, new
BeanPropertyRowMapper<Book>(Book.class));
return bookList;
}
批量操作 使用batchUpdate ,传入的参数是一个list
//批量添加
@Override
public void batchAddBook(List<Object[]> batchArgs) {
String sql = "insert into t_book values(?,?,?)";
int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
System.out.println(Arrays.toString(ints));
}
//批量添加测试
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"3","java","a"};
Object[] o2 = {"4","c++","b"};
Object[] o3 = {"5","MySQL","c"};
batchArgs.add(o1);
batchArgs.add(o2);
batchArgs.add(o3);
//调用批量添加
bookService.batchAdd(batchArgs);
事务操作
配置文件
<!--创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
<!--开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager" ></tx:annotation-driven>
XML 声明式事务管理
第一步 配置事务管理器
第二步 配置通知
第三步 配置切入点和切面
<!--1 创建事务管理器-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--2 配置通知-->
<tx:advice id="txadvice">
<!--配置事务参数-->
<tx:attributes>
<!--指定哪种规则的方法上面添加事务-->
<tx:method name="accountMoney" propagation="REQUIRED"/>
<!--<tx:method name="account*"/>-->
</tx:attributes>
</tx:advice>
<!--3 配置切入点和切面-->
<aop:config>
<!--配置切入点-->
<aop:pointcut id="pt" expression="execution(*
com.atguigu.spring5.service.UserService.*(..))"/>
<!--配置切面-->
<aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
</aop:config
注解实现
@Transactional,这个注解添加到类上面,也可以添加方法上面
- 如果把这个注解添加类上面,这个类里面所有的方法都添加事务
- 如果把这个注解添加方法上面,为这个方法添加事务
Transactional可以定义隔离级别,传播行为等
完全注解声明式事务管理
@Configuration //配置类
@ComponentScan(basePackages = "com.atguigu") //组件扫描
@EnableTransactionManagement //开启事务
public class TxConfig {
//创建数据库连接池
@Bean
public DruidDataSource getDruidDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///user_db");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
//创建 JdbcTemplate 对象
@Bean
public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
//到 ioc 容器中根据类型找到 dataSource
JdbcTemplate jdbcTemplate = new JdbcTemplate();
//注入 dataSource
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
//创建事务管理器
@Bean
public DataSourceTransactionManager
getDataSourceTransactionManager(DataSource dataSource) {
DataSourceTransactionManager transactionManager = new
DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
} }
一般的xml配置内容
实际使用中,一般会使用注解+xml配置来实现spring功能,其中xml配置对上文进行总结,配置内容如下
<?xml version="1.0" encoding="UTF-8"?>
<!--在使用spring 相关jar包的时候进行配置 每个jar包对应一个xmlns和schemaLocation路径-->
<!--格式基本相关 只要修改相关的关键字-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx = "http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 开启注解扫描 ,才可以使用注解 可以使用use-default-filter配合include-filer和exclude-filter使用 -->
<context:component-scan base-package="com.jdbcTemplate" ></context:component-scan>
<!-- 开启aop-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!-- JdbcTemplate使用-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="jdbc:mysql:/book"/>
<property name="username" value = "root"/>
<property name="password" value = "LRY990722"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
</bean>
<bean id="'jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
<bean/>
<!--创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
<!--开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager" ></tx:annotation-driven>
</bean>
</beans>