Spring学习资料以及配置环境

一、Spring4 1、介绍 新特性 SpringIDE 插件 IOC DI 在 Spring 中配置 Bean 自动装配 Bean 之间的关系(依赖、继承) Bean 的作用域 使用外部属性文件 SpEL 管理 Bean 的生命周期 通过工厂方法配置 Bean 通过 FactoryBean 配置 Bean 通过注解配置 Bean 泛型依赖注入 AOP 基础 前置通知 后置通知 返回通知 异常通知 环绕通知 切面的优先级 切点表达式 使用 XML 文件的方式配置 AOP 使用 JdbcTemplate 和 JdbcDaoSupport 使用 NamedParameterJdbcTemplate Spring 的声明式事务 事务的属性(传播行为、隔离级别、回滚属性、只读属性、过期时间) 使用 XML 文件的方式配置事务 整合 Hibernate 整合 Struts2 等。 2、安装maven 1、电脑需要有Java环境 输入java -version 验证 2、下载maven http://maven.apache.org/download.cgi 选择编译过的版本 apache-maven-3.5.0-bin.zip 解压到D盘 D:mvn3.5apache-maven-3.5.0 3、配置环境变量 新建环境变量 M2_HOME=D:mvn3.5apache-maven-3.5.0 添加PATH ;%M2_HOME%in; 验证 mvn -v 4、修改Maven仓库路径 如改为 d:m2 epository 修改配置文件 D:mvn3.5apache-maven-3.5.0confsettings.xml 找到localRepository标记 修改为 D:/m2/repository 注意斜线与linux相同 把settings.xml 文件复制到D:/m2 下 5、maven目录介绍 bin 放置命令文件夹 boot 启动文件夹 默认类加载器 conf 配置文件夹 settings.xml 全局定制maven行为 lib maven运行需要的类库 6、eclipse中安装maven插件 需要网络 help --》 Install new software --》 add 在name输入 m2e 在Location 输入 http://download.eclipse.org/technology/m2e/releases 选中 search到Maven插件 依次点击next 重启eclipse 插件安装成功验证 在Window--》Preferences --》 多了一个Maven选项 7、eclipse中配置maven 在Window--》Preferences --》 Maven选项 点击 Installations 添加自己的maven 点击 User Settings 选择自己的settings.xml 文件 8、工程目录分析 src/main/java java源文件 src/test/java 测试类位置 Maven Dependencies maven依赖的jar文件 target maven编译后文件位置 pom.xml 全称Project Object Model 项目基本信息 src 存放main和test会用到的第三方资源 9、打包 在pox.xml 中 jar 指定打包类型 默认是jar 在项目的根路径下 mvn package 打包 mvn clean 清理包 验证 查看target目录 10、maven创建项目 1、Archetype quickstart 普通java项目 打jar包 webapp web项目 打war包 2、新建webapp项目 1、在项目向导中建立项目 Archetype 选 webapp 2、给项目添加Server Runtime支持 右键项目--》属性--》java build --》 add library --》Server Runtime --》tomcat8 3、查看Deployment Assemb... 确定/src/main/webapp / 3、项目目录介绍 src/main/java 放置java源文件位置 src/main/webapp web根路径 放置前台文件位置 3、安装 eclipse spring插件 需要网络 help --》 Install new software --》 add 选择本地的springsource-tool-suite-3.8.4.RELEASE-e4.6.3-updatesite.zip 选择带IDE的四个选项 下一步 下一步 同意 完成。 重启eclipse 验证 window 首选项中有spring 4、给项目添加spring IOC支持 在pox.xml文件中 添加 org.springframework spring-web 4.0.2.RELEASE 追加jar包 8个 spring-web-4.0.2.RELEASE.jar spring-aop-4.0.2.RELEASE.jar aopalliance-1.0.jar spring-beans-4.0.2.RELEASE.jar spring-context-4.0.2.RELEASE.jar spring-expression-4.0.2.RELEASE.jar spring-core-4.0.2.RELEASE.jar commons-logging-1.1.3.jar org.springframework spring-context 4.0.2.RELEASE 追加jar包 7个 spring-context-4.0.2.RELEASE.jar spring-aop-4.0.2.RELEASE.jar aopalliance-1.0.jar spring-beans-4.0.2.RELEASE.jar spring-core-4.0.2.RELEASE.jar commons-logging-1.1.3.jar spring-expression-4.0.2.RELEASE.jar 重合7个,只需引入一个即可 5、HelloWorld 什么是bean 有无参构造器,有set,get方法的就是bean 1、写一个HelloWorld.java public class HelloWorld { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void hello(){ System.out.println("hello "+name); } } 2、写一个配置文件applicationContext.xml,配置类 3、在主方法中,写代码 ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml"); 这句话是获取IOC容器,这个时候会把所有的bean都初始化,并set给属性赋值 HelloWorld he = (HelloWorld) ac.getBean("helloWorld"); 获取被管理的bean he.hello(); 调用业务方法 6、 IOC和DI 传统 是你要,我给 ioc 你不用要,我给 DI 给的方式 7、配置Bean bean必须有无参构造器,反射方式创建。 id 容器中类的唯一 可以有多个名字,用逗号分隔。 ApplicationContext 代表IOC容器 BeanFactory 基础设置,面向spring本身 BeanFactory ac= new ClassPathXmlApplicationContext("applicationContext.xml"); ApplicationContext 面向开发者 ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml"); ClassPathXmlApplicationContext 从类路径查找 FileSystemXmlApplicationContext 从文件系统查找 BeanFactory ac= new FileSystemXmlApplicationContext("C:\Users\Administrator\workspace3\testmaven3\src\main\resources\applicationContext.xml"); getBean 通过id 推荐用 HelloWorld he = (HelloWorld) ac.getBean("helloWorld"); 通过class 不推荐,不确定有几个class对象。 HelloWorld he = ac.getBean(HelloWorld.class); 基于xml 基于注解 8、注入方式 属性注入 构造注入 位置 类型 区分重载的构造器 工厂方法注入(不常用)知道就可 属性注入细节 基本数据类型+String 1 2 Rose 3 4 jack 5、包含特殊符号 ]]> 对象类型 引用对象类型 内部bean 不用id,只能在内部使用 ]]> null值和级联属性 null值 级联属性 属性先初始化后才可级联处理。struts2 不一样 集合属性 Set t1 t2 t3 Array t1 t2 t3 List t1 t2 t3 Map Properties t1 t2 t3 配置公用的集合 1、引入util命名空间 2、独立集合 t1 t2 t3 3、 ref="carss" 引用集合 使用p命名空间 1、引入p命名空间 2、使用p 比以前代码更加简洁 自动装配 autowire="byName" 通过名称装配 id名称和类属性名称一致,set方式装配 autowire="byType" 通过类型装配 相同类型的bean只能有一个 1、要装配都装配 2、byName ,byType只能2选1 Bean之间的关系 继承 parent="car" 不是java中的继承,就是利用之前bean的配置模板,快速生成新的bean,继承后,只写不同的属性。 不是所有属性都会被继承 如 autowire 、abstract等 abstract="true" 抽象bean 不能实例化 只能被继承 可以不指定class属性,没有class属性的bean一定是抽象bean 依赖 depends-on="car" 用逗号,指定多个bean bean的加载本身没有顺序,通过depends-on 来确定先后顺序 Bean的作用域 默认单例的,用的都是一个实例。 scope="singleton" 加载容器时创建 非单例模式 scope="prototype" 每次请求时加载(懒) 使用外部属性文件 spring 2.5之后 9、spel表达式 用#{表达式} 表达式 可以是直接常量 字符串用'' 动态赋值 可以是其他bean的id 类似于ref 其他bean的属性 id.shuxing 可以调用id.方法 可以通过 T() 调用静态属性 可以用正则 可以用 +-*/ % 可以用 > >= < <= == != 可以用 and or 可以用 ?: 10、bean的生命周期 1、容器 2、生命周期 init-method="" 初始化方法 destroy-method="" 销毁方法 ac.close(); destroy-method 方法会被调用 11、后置处理器 给部分属性赋值,检查属性赋值情况,处理所有的bean 没有id public class MyBeanPost implements BeanPostProcessor 在init-method 方法前后被调用 12、Bean的配置方式 工厂方法 静态工厂方法 获取bean对应的工厂产生的某一个实例 id 指工厂方法中的某一个实例 class 指向静态方法 factory-method="getCar" 指向静态方法名 给静态方法传参数 实例工厂方法 需要创建工厂类对象 工厂类 通过工厂类创建的对象 没有class属性 factory-method="getCar" 指向工厂方法 参数 factory-bean="factory" 指向工厂类id FactoryBean 创建bean spring 提供的 定义一个类,实现FactoryBean 接口 实现三个方法 配置Bean 其他正常使用。 实际调用 factory的getObject方法 13、基于注解配置bean @Component 标识一个受Spring管理的组件 @Resposityor 标识持久层 @Service 标识服务层 @Controller 标识控制层 可以混用 1、配置bean 组件扫描 扫描包 context:commpnent-scan 扫描后,自动生成bean resource-pattern="an/*.class" 指定扫描的资源 包含哪些资源 可以有多个 不包含哪些资源 可以有多个 使用默认的规则 use-default-filters="true" annotation 通过注解过滤 assignable 指定接口或者类 在bean上添加注解 2、自动装配属性 context:commpnent-scan 扫描时自动装配 @Autowired 类型兼容的bean,直接加进来 写在属性或者set方法上面 写在属性上面,不用set方法 不验证元素必须被管理(没bean) @Autowired(require=false) 两个匹配类型 @Autowired 找名字匹配 一个是类型,多个用名字 @Qualifier 这个注解可以提供Bean名称,与@Autowired 一起用 @Resource @Inject 14、泛型依赖注入 父类建立关联类型 父类用T 泛型 @Autowired 放在属性上面,可以被子类继承,属性受保护以上修饰 子类继承这个关系 子类具体类型 子类不写父类继承的属性 二、AOP AOP 是面向切面编程,如日志等功能。 1、动态代理 log案例 方法内部,proxy不要使用 引入案例 2、AspectJ 的AOP 添加支持 org.springframework spring-aop 4.0.2.RELEASE org.aspectj aspectjrt 1.6.11 org.aspectj aspectjweaver 1.6.11 runtime 3、AOP 注解方式: 0、在applicationContext.xml的配置 添加 1、写一个类,写before方法 2、在类中添加另个注解,一个被ioc管理,一个作为aop的切面 @Aspect @Component 3、在方法上写 @Before("execution(public int com.ibc.aop.test1.IComputer.add(int,int))") @Before("execution(public int com.ibc.aop.test1.IComputer.*(int,int))") * 表示所有方法 .. 表示参数任意 在方法中可以获取方法名和参数 point.getSignature().getName() point.getArgs() 4、后置通知,无论方法是否有异常,都会被执行。 不能访问方法执行的结果 @After("execution(public int com.ibc.aop.test1.IComputer.*(int,int))") 5、返回通知, @AfterReturning ,可以有返回值,有异常不执行 @AfterReturning(value="execution(public int com.ibc.aop.test1.IComputer.add(int,int))",returning="ret") public void afterMethod(JoinPoint point,Object ret){ } 6、异常通知, 有异常才会出现 @AfterThrowing(value="execution(public int com.ibc.aop.test1.IComputer.add(..))",throwing="ex") public void afterThrowMethod(JoinPoint point,Exception ex){} 异常类型,可以决定什么异常可以被通知。 7、环绕通知, 环绕通知需要携带ProceedingJoinPoint类型参数 相当于一个完整的动态代理 环绕通知必须有返回值,即目标方法必须有返回值 @Around(value="execution(public int com.ibc.aop.test1.IComputer.add(..))") public Object aroundMethod(ProceedingJoinPoint point){ Object proceed =null; try { //前置 Signature signature = point.getSignature(); System.out.println("method -----@aroundMethod "+signature.getName()+" "+Arrays.toString(point.getArgs())); proceed = point.proceed(); //返回通知 } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); //异常通知 } //后置通知 return proceed; } 8、验证切面 如果有多个切面,可以设置切面的优先级 @Order(1) 数据越小优先级越高 9、重用切点表达式 定义一个模板方法 @Pointcut @Pointcut("execution(public int com.ibc.aop.test1.IComputer.add(..))") public void declareJoinPaint(){} 在类内切点方法上 @After("declareJoinPaint()") public void afterMethod(JoinPoint point){} 在类外方法上 @After("LoggingAspect.declareJoinPaint()") public void afterMethod(JoinPoint point){} 10、基于xml方式 11、JDBCTemplate 1、导入jar包 org.springframework spring-jdbc ${spring.version} 2、配置 3、操作 ApplicationContext ac=new ClassPathXmlApplicationContext("application-mysql.xml"); JdbcTemplate ds=(JdbcTemplate) ac.getBean("jdbcTemplate"); 1、单sql的增删改 int m= ds.update("delete from user where id=?",2); 2、批量增加 List params=new ArrayList(); params.add(new Object[]{2}); //List int[] i=ds.batchUpdate("delete from user where id=?", params); 3、查询单条记录 String sql="select id,uname from user where id=?"; RowMapper rowMapper=new BeanPropertyRowMapper(User.class); User user = ds.queryForObject(sql, rowMapper, 1); 用sql的别名 实现列于属性之间的映射 不支持级联属性 4、查询出集合 String sql="select id,uname from user where id>?"; RowMapper rowMapper=new BeanPropertyRowMapper(User.class); List list=(List) ds.query(sql, rowMapper,0); 5、获取单个属性值 String sql="select count(*) from user"; Long m = ds.queryForObject(sql, Long.class); 12、具名参数JDBCTemplate 维护性高,不用对参数 1、配置 没有无参构造器 2、使用 NamedParameterJdbcTemplate ds=(NamedParameterJdbcTemplate) ac.getBean("namedParameterJdbcTemplate"); Map map =new HashMap<>(); map.put("un", "Rose"); //un 就是具名, 在sql中写 :un int i = ds.update("insert into user(uname) values(:un)",map); 可以像hiberante那样操作,存对象 参数名要与属性名一致 NamedParameterJdbcTemplate ds=(NamedParameterJdbcTemplate) ac.getBean("namedParameterJdbcTemplate"); String sql="insert into user(uname) values(:uname)"; User user=new User("tatata"); SqlParameterSource paramSource=new BeanPropertySqlParameterSource(user); int i =ds.update(sql, paramSource); 13、事务 1、声明式事务 1、添加事务依赖 org.springframework spring-tx ${spring.version} 2、在xml配置文件中,添加事务管理 3、在service方法上面添加注解 @Transactional 2、事务传播行为 一个事务方法调用另外一个事务方法,就是事务传播 required 如果有事务在运行,就在这个事务中工作,如果没有 则新建一个事务,运行。 在事务中运行。 在对应方法上 @Transactional(propagation=Propagation.REQUIRED) required_new 如果有事务在运行,挂起事务,然后新建事务运行, 如果没有事务,则运行新事物。 在自己的事务中运行。 在对应方法上 @Transactional(propagation=Propagation.REQUIRES_NEW) 3、事物的隔离级别 在对应方法上 @Transactional(propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED) 4、默认,对所有运行时异常进行回滚 通常用默认值 @Transactional(rollbackFor={IOException.class},noRollbackFor={SQLException.class}) rollbackFor 回滚的异常类型数组 noRollbackFor 不回滚的异常类型数组 5、是否只读事务,帮助数据库引擎优化 @Transactional(readOnly=true) 6、回滚前最多需要多少时间,单位秒 @Transactional(timeout=3) 可以用sleep方法测试,单位毫秒。 ----- 7、基于xml的方式 在配置文件中配置 --- 回滚的异常类型数组 14、spring整合hibernate4 Spring管理SessionFactory hibernate用spring的事务管理 1、添加支持 org.hibernate hibernate-core ${org.hibernate-version} commons-dbcp commons-dbcp 1.4 org.springframework spring-hibernate 1.2.9 2、添加配置文件 15、在eclipse中添加hibernate插件 1、hibernate Tools 的离线安装 确定eclipse的版本是neon help --》 Install new software --》 add 在Location 输入 选择本地的插件 jbosstools-4.4.4.Final-updatesite-core.zip 点击JBoss Web and Java EE Development 选择Hibernate Tools 打√, 取消Contact all update sites during install to find required software 依次点击next 重启eclipse 2、hibernate.cfg.xml 数据源移到spring中 关联的hbm.xml 移到spring中 需要配置 hibernate的基本属性:方言,SQL显示格式化,生成数据表的策略以及二级缓存等。 16、可以不用hibernate.cfg.xml org.hibernate.dialect.MySQLDialect true true update 17、spring 整合 Struts2 通过监听器整合 ServletContextListener 里面创建ApplicationContext 比较合适。 1、添加jar包 org.springframework spring-web 4.0.2.RELEASE org.springframework spring-core 4.0.2.RELEASE 2、写一个ServletContextListener 创建一个ApplicationContext对象, 放入ServletContext范围中 可以建立一个Context-param 把配置名称导入进来。 3、创建一个Servlet,在Servlet中获取AC,然后获得bean,做输出。 18、spring 在web中应用 1、在web.xml中 添加一个context-param contextConfigLocation classpath:applicationContext.xml 2、配置ioc org.springframework.web.context.ContextLoaderListener 3、在jsp中 ApplicationContext ac=WebApplicationContextUtils.getWebApplicationContext(application); 19、spring 集成struts2 管理struts2的anction 1、添加jar包 org.apache.struts struts2-core 2.3.16.3 org.apache.struts struts2-spring-plugin 2.3.16.3 2、在web.xml中 注意:struts.xml 默认是放在src的类路径下,现在我把它放在/WEB-INF/ 下了,另外,需要额外添加 struts-default.xml,struts-plugin.xml 两个配置信息。 ***这是web容器连接struts2的连接点 配置的Action默认后缀是 .action struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter config struts-default.xml,struts-plugin.xml,../struts.xml struts2 /* 2、 在applicationContext.xml中配置Action beans 注意添加属性 scopt=prototype 表示不是单例的 3、 在struts.xml中的action中的class属性配置 spring bean的id /ok.jsp 注意 class="helloAction" 与 id="helloAction" 相同 20、spring 集成springmvc 1、添加jar包 org.springframework spring-core 4.0.2.RELEASE org.springframework spring-webmvc 4.0.2.RELEASE 2、在web.xml中配置springmvc springDispatcherServlet org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:springmvc.xml 1 springDispatcherServlet / 3、定义springmvc.xml文件 扫描IOC类 统一处理方法返回值前后缀 4、定义一个类用@Controller修饰,表示自动被扫描 定义一个带String返回值的方法 用@RequestMapping("/helloworld") 修饰 表示url地址 @Controller public class HelloWorld { @RequestMapping("/helloworld") public String sayHello(){ System.out.println("Hello MVC"); return "success"; } } [访问用helloworld.do] 返回页面 prefix+"success"+ suffix 做转发操作 5、index.jsp helloworld 21、spring集成mybatis 1、添加jar包 mysql mysql-connector-java 5.1.18 org.springframework spring-jdbc 4.0.2.RELEASE c3p0 c3p0 0.9.1.2 org.mybatis mybatis 3.4.1 org.mybatis mybatis-spring 1.3.0 2、编写 com.ibc.test.User 类 注意,要求序列化 @Component public class User implements Serializable{ private Integer id; private String uname; ...... } 3、编写User-sqlmap-mapping.xml insert into user(uname) values(#{uname}) UPDATE USER SET uname=#{uname} WHERE ID=#{id} DELETE USER WHERE ID=#{id} 4、编写 mybatis.xml 5、编写 db.properties url=jdbc:mysql:///test user=root password=root driver=com.mysql.jdbc.Driver 6、编写spring.mybatis.xml 文件 classpath:db.properties 7、测试类 ApplicationContext ac=new ClassPathXmlApplicationContext("spring.mybatis.xml"); SqlSessionTemplate sqlSessionTemplate= (SqlSessionTemplate) ac.getBean("sqlSessionTemplate"); List list = sqlSessionTemplate.selectList("queryAll"); System.out.println(list); 22、配置文件相关的注解方法 1、定义一个类 @Configuration 表示这个类是一个类似于ApplicationContext.xml的类文件 @ComponentScan("com.ibc.ssm") //表示IOC要扫描的包 public class Config { } 2、测试 ApplicationContext ac=new AnnotationConfigApplicationContext(Config.class); User user=ac.getBean(User.class); System.out.println(user); 号外: 通过注解方式定义AOP切面 1、写一个配置类 @Configuration @ComponentScan("com.ibc.demo") @EnableAspectJAutoProxy public class Config {} 2、定义一个切面 @Component @Aspect public class LogAspect { @Pointcut("execution( * set* (. .))") public void myPointCut(){} @Before("myPointCut()") public void beforeMechod(JoinPoint point){ System.out.println("----beforeMechod--------"+point.getSignature().getName()+" "+point.getArgs()); } } 3、定义一个实体类 @Component public class User implements Serializable { private String username; private Integer uid; private String password; 。。。。。。 } 4、测试类 @Test public void testUser(){ ApplicationContext ac=new AnnotationConfigApplicationContext(Config.class); User user=ac.getBean(User.class); user.setUsername("tom"); System.out.println(user); }
原文地址:https://www.cnblogs.com/LangZiXiYan/p/7052455.html