Spring

spring简介

实习笔记[Spring] - 图1 Ssh: struts+spring+hibernate Ssm:spring+springmvc+mybatis

Spring 4.0以上版本升级

MyBatis3.4.2为分水岭

druid 版本1.2.0以上

junit 版本为4.12以上

Springioc简介

控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫“依赖查找”(Dependency Lookup)。通过控制反转,对象在被创建的时候,由一个调控系统内所有对象的外界实体将其所依赖的对象的引用传递给它。也可以说,依赖被注入到对象中。

其实就是将new对象的权利交给spring容器去管理,我们用到对象的时候,直接去springioc容易中拿对象即可,降低代码之间的耦合度

实习笔记[Spring] - 图2

springioc的入门案例

在springioc容器默认采用单例模式,也可以切换成多例

1. 创建userbean

  1. public class UserBean {
  2. private int uid;
  3. private String uname;
  4. private String address;
  5. //alt+insert 生成get/set/tostring
  6. }

2. 导入pom依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-context</artifactId>
  5. <version>5.2.5.RELEASE</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>junit</groupId>
  9. <artifactId>junit</artifactId>
  10. <version>4.12</version>
  11. </dependency>
  12. </dependencies>

3. 在resources下面创建spring.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
  6. <bean class="com.ujiuye.bean.UserBean" id="u1"></bean>
  7. <!--scope="prototype"多例 singleton单例-->
  8. <bean class="com.ujiuye.bean.UserBean" name="u2,u3" scope="prototype"/>
  9. </beans>

测试

  1. @Test
  2. public void t1(){
  3. //之前创建对象
  4. // UserBean u=new UserBean();
  5. ApplicationContext app=new ClassPathXmlApplicationContext("spring.xml");
  6. UserBean u= (UserBean) app.getBean("u3");
  7. UserBean u2= (UserBean) app.getBean("u3");
  8. System.out.println(u==u2);
  9. }

依赖注入(DI)

给属性赋值:

1. 通过set方法赋值:

实习笔记[Spring] - 图3

2. 通过构造方法赋值:

<bean class="com.ujiuye.bean.UserBean" id="u1"></bean>;相当于写了 UserBean u1=new UserBean();

实习笔记[Spring] - 图4

实习笔记[Spring] - 图5

ref属性,指向当前属性依赖的另外一个对象

  1. public class PersonBean {
  2. private int pid;
  3. private String pname;
  4. private CardBean card;
  5. public PersonBean(int pid, String pname) {
  6. this.pid = pid;
  7. this.pname = pname;
  8. }
  9. // alt+insert 生成get/set/toString
  10. }
  1. public class CardBean {
  2. private int cid;
  3. private String cnum;
  4. }

Spring.xml

  1. <bean class="com.ujiuye.bean.PersonBean" id="p1">
  2. <!-- <constructor-arg name="pid" value="100"/>
  3. <constructor-arg name="pname" value="admin"/>-->
  4. <constructor-arg index="0" value="100"/>
  5. <constructor-arg index="1" value="admin"/>
  6. <!-- <property name="card">
  7. <bean class="com.ujiuye.bean.CardBean">
  8. <property name="cid" value="111"/>
  9. <property name="cnum" value="110"/>
  10. </bean>
  11. </property>-->
  12. <property name="card" ref="card"></property>
  13. </bean>
  14. <bean class="com.ujiuye.bean.CardBean" id="card">
  15. <property name="cid" value="111"/>
  16. <property name="cnum" value="110"/>
  17. </bean>

测试:

  1. @Test
  2. public void t2(){
  3. ApplicationContext app=new ClassPathXmlApplicationContext("spring.xml");
  4. PersonBean p1= (PersonBean) app.getBean("p1");
  5. System.out.println(p1);
  6. }

3. springioc注入各种集合

  1. 实体类
  1. public class CardBean {
  2. private int cid;
  3. private String cnum;
  4. private List list;
  5. private List<PersonBean> ps;
  6. private Set set;
  7. private Map map;
  8. //alt+insert 生成get/set/toString
  9. }
  1. Spring.xml配置
  1. <bean class="com.ujiuye.bean.CardBean" id="card">
  2. <property name="cid" value="111"/>
  3. <property name="cnum" value="110"/>
  4. <property name="list">
  5. <list>
  6. <value>1111</value>
  7. <value>2222</value>
  8. <value>3333</value>
  9. </list>
  10. </property>
  11. <property name="set">
  12. <set>
  13. <value>aaa</value>
  14. <value>aaa</value>
  15. <value>bbb</value>
  16. </set>
  17. </property>
  18. <property name="map">
  19. <map>
  20. <entry key="name">
  21. <value>张三</value>
  22. </entry>
  23. <entry key="password">
  24. <value>123456</value>
  25. </entry>
  26. </map>
  27. </property>
  28. <property name="ps">
  29. <list>
  30. <bean class="com.ujiuye.bean.PersonBean">
  31. <constructor-arg name="pid" value="1"/>
  32. <constructor-arg name="pname" value="aaa"/>
  33. </bean>
  34. <bean class="com.ujiuye.bean.PersonBean">
  35. <constructor-arg name="pid" value="2"/>
  36. <constructor-arg name="pname" value="bbb"/>
  37. </bean>
  38. <bean class="com.ujiuye.bean.PersonBean">
  39. <constructor-arg name="pid" value="3"/>
  40. <constructor-arg name="pname" value="cc"/>
  41. </bean>
  42. </list>
  43. </property>
  44. </bean>
  1. 测试
  1. @Test
  2. public void t3(){
  3. ApplicationContext app=new ClassPathXmlApplicationContext("spring.xml");
  4. CardBean p1= (CardBean) app.getBean("card");
  5. System.out.println(p1);
  6. }

Springioc对多态的支持

利用spring+springjdbc curd

1. Pom 坐标依赖

  1. <!--mysql驱动-->
  2. <dependency>
  3. <groupId>mysql</groupId>
  4. <artifactId>mysql-connector-java</artifactId>
  5. <version>5.1.26</version>
  6. </dependency>
  7. <!--spring-jdbc-->
  8. <dependency>
  9. <groupId>org.springframework</groupId>
  10. <artifactId>spring-jdbc</artifactId>
  11. <version>5.2.5.RELEASE</version>
  12. </dependency>
  13. <!--druid数据源-->
  14. <dependency>
  15. <groupId>com.alibaba</groupId>
  16. <artifactId>druid</artifactId>
  17. <version>1.2.0</version>
  18. </dependency>

2. 书写PersonDao

  1. public interface PersonDao {
  2. int add(PersonBean p);
  3. int del(int id);
  4. int update(PersonBean p);
  5. List<PersonBean> findAll();
  6. }

3. personDaoImpl

  1. public class PersonDaoImpl implements PersonDao {
  2. //spring-jdbc 的工具类
  3. private JdbcTemplate template;
  4. public JdbcTemplate getTemplate() {
  5. return template;
  6. }
  7. public void setTemplate(JdbcTemplate template) {
  8. this.template = template;
  9. }
  10. @Override
  11. public int add(PersonBean p) {
  12. String sql="insert person(pname)values(?)";
  13. return template.update(sql,p.getPname());
  14. }
  15. @Override
  16. public int del(int id) {
  17. String sql="delete from person where pid=?";
  18. return template.update(sql,id);
  19. }
  20. @Override
  21. public int update(PersonBean p) {
  22. String sql="update person set pname=? where pid=?";
  23. return template.update(sql,p.getPname(),p.getPid());
  24. }
  25. @Override
  26. public List<PersonBean> findAll() {
  27. String sql="select* from person";
  28. List<PersonBean> list = template.query(sql, new RowMapper<PersonBean>() {
  29. @Override
  30. public PersonBean mapRow(ResultSet resultSet, int i) throws SQLException {
  31. PersonBean p=new PersonBean();
  32. p.setPid(resultSet.getInt("pid"));
  33. p.setPname(resultSet.getString("pname"));
  34. return p;
  35. }
  36. });
  37. return list;
  38. }
  39. }
  1. public class PersonDaoImpl implements PersonDao {
  2. //spring-jdbc 的工具类
  3. private JdbcTemplate template;
  4. public JdbcTemplate getTemplate() {
  5. return template;
  6. }
  7. public void setTemplate(JdbcTemplate template) {
  8. this.template = template;
  9. }
  10. @Override
  11. public int add(PersonBean p) {
  12. String sql="insert person(pname)values(?)";
  13. return template.update(sql,p.getPname());
  14. }
  15. @Override
  16. public int del(int id) {
  17. String sql="delete from person where pid=?";
  18. return template.update(sql,id);
  19. }
  20. @Override
  21. public int update(PersonBean p) {
  22. String sql="update person set pname=? where pid=?";
  23. return template.update(sql,p.getPname(),p.getPid());
  24. }
  25. @Override
  26. public List<PersonBean> findAll() {
  27. String sql="select* from person";
  28. List<PersonBean> list = template.query(sql, new RowMapper<PersonBean>() {
  29. @Override
  30. public PersonBean mapRow(ResultSet resultSet, int i) throws SQLException {
  31. PersonBean p=new PersonBean();
  32. p.setPid(resultSet.getInt("pid"));
  33. p.setPname(resultSet.getString("pname"));
  34. return p;
  35. }
  36. });
  37. return list;
  38. }
  39. }

4. PersonSerice

  1. public class PersonSerice {
  2. private PersonDao dao;
  3. public PersonDao getDao() {
  4. return dao;
  5. }
  6. public void setDao(PersonDao dao) {
  7. this.dao = dao;
  8. }
  9. /**添加
  10. * @param p
  11. * @return
  12. */
  13. public int add(PersonBean p){
  14. return dao.add(p);
  15. }
  16. public int del(int id){
  17. return dao.del(id);
  18. }
  19. public int update(PersonBean p){
  20. return dao.update(p);
  21. }
  22. public List<PersonBean> findAll(){
  23. return dao.findAll();
  24. }
  25. }

5. Spring.xml

实习笔记[Spring] - 图6

  1. <bean class="com.ujiuye.service.PersonSerice" id="personService">
  2. <property name="dao" ref="personDao"/>
  3. </bean>
  4. <bean class="com.ujiuye.dao.PersonDaoImpl" id="personDao">
  5. <property name="template" ref="template"/>
  6. </bean>
  7. <bean class="org.springframework.jdbc.core.JdbcTemplate" id="template">
  8. <property name="dataSource" ref="dataSource"></property>
  9. </bean>
  10. <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
  11. <property name="url" value="jdbc:mysql://localhost:3306/tt?characterEncoding=utf-8"/>
  12. <property name="username" value="root"/>
  13. <property name="password" value="123456"/>
  14. <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  15. </bean>

6. 测试

  1. @Test
  2. public void t1(){
  3. ApplicationContext app=new ClassPathXmlApplicationContext("spring.xml");
  4. PersonSerice serice= (PersonSerice) app.getBean("personService");
  5. PersonBean p=new PersonBean(13,"zzzz");
  6. // serice.add(p);
  7. // serice.del(11);
  8. // serice.update(p);
  9. List<PersonBean> list = serice.findAll();
  10. System.out.println(list);
  11. }

springioc注解的使用

1. 常用的注解

Springboot 极力推崇使用注解的方式配置。 1.配置bean的注解,相当于我们在xml中写了 @Component ,@ Repository ,@Service @Controller 注解放在类名上。如果没有给id的名字,直接默认以类名的首字母小写作为bean的id 将来项目要分为三层架构:

  1. dao (data access object) 数据访问层 @ Repository
  2. Service 业务层 (通过调用dao层整合成一个完整的业务),@Service
  3. Controller 控制层(控制页面的跳转) @Controller
  4. 如果有一层不好归纳与三层架构的任何一层,我们直接@Component

@Value 放在属性名上的,相当于在

@Autowired 注入,相当于在xml配置引用,可以自动从容器中寻找对应的类型,自动注入,而且可以省略get/set方法

@Resouce 和@AutoWired作用相同,但是他是jdk的注解 @Resouce(name= “id名”)

2. 案例1

1.改造personbean和cardBean
  1. @Component("pp")
  2. @Scope("prototype") //设置是否单例
  3. public class PersonBean {
  4. @Value("100")
  5. private int pid;
  6. @Value("张三")
  7. private String pname;
  8. @Autowired
  9. private CardBean card;
  10. }

实习笔记[Spring] - 图7

2.spring_annotation.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  7. <!--扫描注解-->
  8. <context:component-scan base-package="com.ujiuye.bean"/>
  9. </beans>

3. 单元测试
  1. @Test
  2. public void t1(){
  3. ApplicationContext app=new ClassPathXmlApplicationContext("spring_annotation.xml");
  4. PersonBean p= (PersonBean) app.getBean("pp"); //alt+enter 直接强转
  5. PersonBean p2= (PersonBean) app.getBean("pp");
  6. System.out.println(p);
  7. System.out.println(p==p2);
  8. }

改造上午 spring-jdbc 使用注解

1. 导入spring-test
  1. <!--spring-test-->
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-test</artifactId>
  5. <version>5.2.5.RELEASE</version>
  6. </dependency>

2. 改造dao层接口的实现类

实习笔记[Spring] - 图8

3. 改造UserService

实习笔记[Spring] - 图9

4. 利用spring-test
  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(locations = {"classpath:spring.xml"})
  3. public class SpringTest {
  4. @Autowired
  5. private PersonSerice serice;
  6. @Test
  7. public void t1(){
  8. List<PersonBean> list = serice.findAll();
  9. System.out.println(list);
  10. }
  11. }

5. Spring.xml改造

实习笔记[Spring] - 图10

Spring整合mybatis

实习笔记[Spring] - 图11

1. Pom坐标

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-context</artifactId>
  5. <version>5.2.5.RELEASE</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>junit</groupId>
  9. <artifactId>junit</artifactId>
  10. <version>4.12</version>
  11. </dependency>
  12. <!--mysql驱动-->
  13. <dependency>
  14. <groupId>mysql</groupId>
  15. <artifactId>mysql-connector-java</artifactId>
  16. <version>5.1.26</version>
  17. </dependency>
  18. <!--druid数据源-->
  19. <dependency>
  20. <groupId>com.alibaba</groupId>
  21. <artifactId>druid</artifactId>
  22. <version>1.2.0</version>
  23. </dependency>
  24. <!--spring-test-->
  25. <dependency>
  26. <groupId>org.springframework</groupId>
  27. <artifactId>spring-test</artifactId>
  28. <version>5.2.5.RELEASE</version>
  29. </dependency>
  30. <!--mybatis-spring-->
  31. <dependency>
  32. <groupId>org.mybatis</groupId>
  33. <artifactId>mybatis-spring</artifactId>
  34. <version>2.0.2</version>
  35. </dependency>
  36. <!--mybatis-->
  37. <dependency>
  38. <groupId>org.mybatis</groupId>
  39. <artifactId>mybatis</artifactId>
  40. <version>3.4.2</version>
  41. </dependency>
  42. </dependencies>

2. 创建PersonBean

  1. public class PersonBean {
  2. private int pid;
  3. private String pname;
  4. }

3. 创建PersonDao接口

  1. public interface PersonDao {
  2. int add(PersonBean p);
  3. int del(int id);
  4. int update(PersonBean p);
  5. List<PersonBean> findAll();
  6. }

4. 创建PersonService

  1. @Service
  2. public class PersonService {
  3. @Autowired
  4. private PersonDao dao;
  5. /**添加
  6. * @param p
  7. * @return 成功/失败
  8. */
  9. public boolean add(PersonBean p){
  10. return dao.add(p)>0?true:false;
  11. }
  12. public boolean del(int id){
  13. return dao.del(id)>0?true:false;
  14. }
  15. public boolean update(PersonBean p){
  16. return dao.update(p)>0?true:false;
  17. }
  18. public List<PersonBean> findAll(){
  19. return dao.findAll();
  20. }
  21. }

5. Mybatis_conf.xml 核心配置文件

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. </configuration>

6. PersonMapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.ujiuye.dao.PersonDao">
  6. <insert id="add" parameterType="com.ujiuye.bean.PersonBean">
  7. insert into person (pname) values (#{pname});
  8. </insert>
  9. <delete id="del">
  10. delete from person where pid=#{0}
  11. </delete>
  12. <update id="update" parameterType="com.ujiuye.bean.PersonBean">
  13. update person set pname=#{pname} where pid=#{pid}
  14. </update>
  15. <select id="findAll" resultType="com.ujiuye.bean.PersonBean">
  16. select * from person
  17. </select>
  18. </mapper>

7. Spring.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  7. <!--包扫描-->
  8. <context:component-scan base-package="com.ujiuye"/>
  9. <!--配置数据源-->
  10. <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
  11. <property name="url" value="jdbc:mysql://localhost:3306/tt?characterEncoding=utf-8"/>
  12. <property name="username" value="root"/>
  13. <property name="password" value="123456"/>
  14. <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  15. </bean>
  16. <bean class="org.mybatis.spring.SqlSessionFactoryBean">
  17. <!--配置数据源-->
  18. <property name="dataSource" ref="dataSource"/>
  19. <!--配置mybatis的核心配置文件-->
  20. <property name="configLocation" value="classpath:mybatis/mybatis_conf.xml"/>
  21. <!--配置mapper.xml文件-->
  22. <property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"/>
  23. </bean>
  24. <!--配置dao层接口-->
  25. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  26. <property name="basePackage" value="com.ujiuye.dao"/>
  27. </bean>
  28. </beans>

8. 单元测试

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(locations = "classpath:spring.xml")
  3. public class Spring_MybatisTest {
  4. @Autowired
  5. private PersonService service;
  6. @Test
  7. public void t1(){
  8. PersonBean p=new PersonBean();
  9. p.setPname("xyz");
  10. p.setPid(13);
  11. // boolean success = service.add(p);
  12. // boolean success = service.del(14);
  13. /* boolean success = service.update(p);
  14. System.out.println(success);*/
  15. List<PersonBean> list = service.findAll();
  16. System.out.println(list);
  17. }
  18. }