您的位置:首页 > 编程语言 > Java开发

Spring 3.x 企业开发实战Chapter2 Part1

2016-10-10 11:19 295 查看
需要什么包就导入什么包,没道全也没什么,等控制台报错缺什么包就导入就是了(先把Trace复制到notepad++里面方便查看)。

学习笔记:

(1)<context:component-scan>使用说明:在xml配置了这个标签后,spring可以自动去扫描base-pack下面或者子包下面的Java文件,如果扫描到有@Component
@Controller@Service等这些注解的类,则把这些类注册为bean,这也是为什么不用再注册类似jdbcTemplate这样的对象了,感觉特别屌。。。。

(2)注意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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<context:component-scan base-package="dao" />
<context:component-scan base-package="service" />

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/sampledb"
p:username="root"
p:password="1"/>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource"/>

<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>

<aop:config proxy-target-class="true">
<aop:pointcut id="serviceMethod"
expression=" execution(* service..*(..))"/>
<aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" />
</aop:config>

<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>

</beans>


package dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import domain.LoginLog;

@Repository
public class LoginLogDao {

@Autowired
private JdbcTemplate jdbcTemplate;

public void insertLoginLog(LoginLog loginLog) {
String sql = "insert into t_login_log(user_id, ip, login_datetime) values(?,?,?)";
Object[] args = {loginLog.getUserId(), loginLog.getIp(), loginLog.getLoginDate()};
jdbcTemplate.update(sql, args);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: