发表于: 2017-06-19 00:28:56
1 1292
写在前面:
这个日报参考了师兄:
http://www.jnshu.com/daily/23420?dailyType=others&total=48&page=32&uid=11605&sort=0&orderBy=3
按照自己的理解断断续续花了好长时间按照他的思路敲出来。一开始对于Spring+Mybatis+log4j+Junit几个怎么整合困扰了我好长时间,因为网上找的确实太乱
他的这篇日报流程写的相当好,值得推荐。
Spring是一个基于控制反转(Inversion of Control)的轻量的框架,它的主要实现方式是依赖查找和依赖注入。
======================================================================================================
1控制反转(IOC)代码演示:
先建立一个普通的对象
//普通的Java对象
package com.rcc.pojo;
public class Student {
int id;
String name;
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
}
--------------------------
//applicationContext.xml配置
//前面的几乎一样
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id ="c" class="com.rcc.pojo.Student">
<property name = "name" value = "student2" >
</property>
</bean>
</beans>
-----------------------------------
//测试文件
package demo;
//import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.rcc.pojo.Student;
public class Test {
public static void main(String[] args){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] {"applicationContext.xml"});
//前面的师兄是下面(被注释了)这种写法,但是这种会出现警告:Resource leak: 'context' is never closed
//我按照网上的更改了一下(注意context的类型)
// ApplicationContext context = new ClassPathXmlApplicationContext(
// new String[] { "applicationContext.xml" });
Student c=(Student)context.getBean("c");
System.out.println(c.getName());
context.close();
}
}
//对上面的一些总结,在本程序中,name的参数被放到了applicationContext.xml中,测试时Spring更具xml配置文件自动将其注入new的
//新对象(context)里,而不是和传统方法那样,另外那句代码也可以写成:
//ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
===================================================================================================================
2.依赖注入:spring在创建Product时自动注入Student.
两个基本类:
1.product类:
package com.rcc.pojo;
public class Product {
int id;
String name;
Student student;
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public Student getStudent(){
return student;
}
public void setStudent(Student student){
this.student=student;
}
——————————————————————
}
2.Student类
//普通的Java对象
package com.rcc.pojo;
public class Student {
int id;
String name;
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
}
------------------------------------
//配置applicationgContext.xml
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
//注意两者之间的关系,ref把将St注入到Product中的student.
<bean id ="St" class="com.rcc.pojo.Student">
<property name ="name" value ="student1"></property>
</bean>
<bean id ="Product" class="com.rcc.pojo.Product">
<property name = "name" value = "Product1" ></property>
<property name ="student" ref ="St"></property>
</bean>
</beans>
-----------------------------------------
//测试类
package demo;
//import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.rcc.pojo.Product;
public class Test {
public static void main(String[] args){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
// new String[] {"applicationContext.xml"});
// ApplicationContext context = new ClassPathXmlApplicationContext(
// new String[] { "applicationContext.xml" });
Product p =(Product)context.getBean("Product");
System.out.println(p.getName());
// Student c=(Student)context.getBean("c");
System.out.println(p.getStudent().getName());
context.close();
}
}
结果:
Product1
student1
测试
==========================================================
用注解方式来配置上面的那个例子
师兄的这句不知道是错了,还是我理解的有问题:“在Student.java的student属性前加上@Autowired注解”
应该是在:“Product.java里的:Student student;这上面加入@Autowired注解”(此时可以省略set方法,或不省略直接在set方法上加)
@Autowired 与@Resource都可以让spring自动装配,不过,@Autowired 是框架里的,而@Resource
是java自带的(导入的包分别为:import org.springframework.beans.factory.annotation.Autowired;
和 import javax.annotation.Resource;两者的也些差别@Resources默认按名字,@Autowired默认按类型)
@Component直接在类前面加,表明此类是bean,此时,这个类需要直接在初始化
------
Student 类
//普通的Java对象
package com.rcc.pojo;
import org.springframework.stereotype.Component;
@Component
public class Student {
int id;
String name = "Student1";
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
}
----------
普通Product类
@Autowired
//@Resource (name = "studentresource")
Student student;
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public Student getStudent(){
return student;
}
/**
public void setStudent(Student student){
this.student=student;
}
*/
}
------------
配置文件
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.rcc.pojo"/>
<!-- <bean name ="studentresource" class="com.rcc.pojo.Student">
<property name ="name" value ="Student1"></property>
</bean>
<bean id ="product" class="com.rcc.pojo.Product">
<property name = "name" value = "Product1" ></property>
<property name ="student" ref ="St"></property>
</bean> -->
</beans>
------------------
测试类
package demo;
//import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.rcc.pojo.Product;
public class Test {
public static void main(String[] args){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
// new String[] {"applicationContext.xml"});
// ApplicationContext context = new ClassPathXmlApplicationContext(
// new String[] { "applicationContext.xml" });
Product p =(Product)context.getBean("product");
System.out.println(p.getName());
// Student c=(Student)context.getBean("c");
System.out.println(p.getStudent().getName());
System.out.println("测试");
context.close();
}
}
==========================================================
当某些特殊的业务类需要贯穿整个业务的时候,我们可以称它为切面类,如日志,性能等。
切面类和业务类分别开发,再“编织”在一起。
-------------------------------------------------
业务类
package com.rcc.service;
import org.springframework.stereotype.Component;
@Component("ds")
public class Service {
public void doService(){
System.out.println("doservice");
}
}
--------------------------------------------
切面类
package com.rcc.aspect;
import org.springframework.stereotype.Component;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
@Aspect
@Component("as")
public class LoggerAspect {
@Around("execution(*com.rcc.service.Service.*(..))")
public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("start log:" + joinPoint.getSignature().getName());
Object object = joinPoint.proceed();
System.out.println("end log:" + joinPoint.getSignature().getName());
return object;
}
}
------------------------------------------
配置文件
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 声明业务对象 -->
<!-- <bean name="ds" class="com.rcc.service.Service">
</bean>
-->
<!-- 声明日志切面 -->
<bean id="loggerAspect" class="com.rcc.aspect.LoggerAspect"/>
<aop:config>
<!-- 先指出连接点pointcut,就是spring允许你是通知(Advice)的地方,
基本每个方法的钱、后(两者都有也行),
或抛出异常是时都可以是连接点,spring只支持方法连接点。 -->
<aop:pointcut id="loggerCutpoint"
expression=
"execution(* com.rcc.service.Service.*(..)) "/>
<!-- 再指出切面 -->
<aop:aspect id="logAspect" ref="loggerAspect">
<aop:around pointcut-ref="loggerCutpoint" method="log"/>
</aop:aspect>
</aop:config>
<!-- //扫描两个包
<context:component-scan base-package="com.rcc.aspect"/>-->
<context:component-scan base-package="com.rcc.service"/>
<!--
//进行切面配置
<aop:aspectj-autoproxy/>
-->
</beans>
---------------------------------------
测试
package com.rcc.test;
//import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.rcc.service.Service;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
Service s = (Service) context.getBean("ds");
s.doService();
context.close();
}
}
=============================================================
Spring-Mybatis的配置
程序要连接数据库:
1.先定位到:Mybatis-config.xml,通过配置文件定位到数据库
2.再通过Student.xml执行
3.返回并封装在Student里面
4.把多个Student对象封装在一个集合中
5.返回这个集合
---------------------------------------------
基本类
package com.jnshu.pojo;
public class Student {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
------------------------
Student.xml配置
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.rcc.pojo">
<select id= "listStudent" resultType="Student">
select * from student
</select>
</mapper>
-------------------------
mybatis-config.xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.rcc.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
//数据库信息
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456789"/>
</dataSource>
</environment>
</environments>
<mappers>
//Student.xml的位置
<mapper resource="com/rcc/pojo/Student.xml"/>
// <mapper class="com.rcc.pojo.Student"/>
</mappers>
</configuration>
-----------------------
测试类
package rcc;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.rcc.pojo.Student;
public class Test {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session=sqlSessionFactory.openSession();
List<Student> cs=session.selectList("listStudent");
for (Student c : cs) {
System.out.println(c.getName());
}
}
}
===================================
Spring和Mybatis的整合
主要是理清其中的逻辑关系
-----------------------------
基本类
package com.rcc.pojo;
//import org.springframework.stereotype.Component;
//import org.springframework.stereotype.Component;
//@Component
//import org.springframework.beans.factory.annotation.Autowired;
//@Component("c")
public class Student {
private int id;
//private String name ;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString(){
return "Student [id="+id+",name="+name+"]";
}
}
---------------------------------------------
先定义一个公开的接口
package com.rcc.mapper;
import java.util.List;
//import org.apache.ibatis.annotations.Delete;
//import org.apache.ibatis.annotations.Insert;
//import org.apache.ibatis.annotations.Select;
//import org.apache.ibatis.annotations.Update;
//import org.apache.ibatis.annotations.Select;
import com.rcc.pojo.Student;
public interface StudentMapper {
// @Insert(" insert into Student ( name ) values (#{name}) ")
public int add(Student student);
// @Delete(" delete from Student where id= #{id} ")
public void delete(int id);
// @Select("select * from Student where id= #{id} ")
public Student get(int id);
// @Update("update Student set name=#{name} where id=#{id} ")
public int update(Student student);
// @Select(" select * from Student ")
public List<Student> list();
}
------------------------------
下面是映射文件Student.xml
namespace 命名空间,用于隔离SQL语句
parameterType 定义SQL输入映射类型,MyBatis通过OGNL从输入对象中获取参数传入SQL语句.
resultType 定义SQL输出映射类型,MyBatis将SQL查询结果的一行记录映射为resultType指定的类型.
mapper映射文件名有UserDAO.xml/UserMapper.xml/User.xml等几种形式, 其一般存放在与mybatis-configuration.xml同级的mapper目录下,由于其主要作用为定义SQL语句与映射关系, 因此一般统称为mapper映射文件.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.rcc.mapper.StudentMapper">
<!-- <select id="listStudent" resultType="Student">
select * from Student
</select>
//下面的配置顺序要和下一列标的一样,不然会报错
The content of element type "mapper" must match "(cache-ref|cache|resultMap*|parameterMap*|sql*|insert*|update*|
delete*|select*)+".
-->
<insert id="add" parameterType="Student" >
insert into Student ( name ) values (#{name})
</insert>
<delete id="delete" parameterType="Student" >
delete from Student where id= #{id}
</delete>
<select id="get" parameterType="_int" resultType="Student">
select * from Student where id= #{id}
</select>
<update id="update" parameterType="Student" >
update Student set name=#{name} where id=#{id}
</update>
<select id="list" resultType="Student">
select * from Student
</select>
</mapper>
----------------------------------------------------
spring 配置文件applicateContext.xml
<?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:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>1084722107</value>
</property>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="typeAliasesPackage" value="com.rcc.pojo" />
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:com/rcc/mapper/*.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.rcc.mapper"/>
</bean>
</beans>
--------------------------------------
测试类
package com.rcc.test;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.rcc.mapper.StudentMapper;
import com.rcc.pojo.Student;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestMybatis {
@Autowired
private StudentMapper studentMapper;
@Test
public void cTest(){
System.out.println("测试3");
}
@Test
public void testAdd() {
Student student = new Student();
student.setName("新2");
studentMapper.add(student);
}
@Test
public void testList() {
System.out.println(studentMapper);
List<Student> cs=studentMapper.list();
for (Student c : cs) {
System.out.println(c.getName());
}
}
}
---------------------------------------------
计划:总结任务一,开始任务二
遇到的问题:主要是配置文件经常出现字母打错出现的各种错误,也已经根据报的错误找出来了。
收获:主要还是理清Spring+Mybatis+log4j+Junit和它们各个对象之间的逻辑关系。
评论