Spring
spring简介
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容易中拿对象即可,降低代码之间的耦合度
springioc的入门案例
在springioc容器默认采用单例模式,也可以切换成多例
1. 创建userbean
public class UserBean {
private int uid;
private String uname;
private String address;
//alt+insert 生成get/set/tostring
}
2. 导入pom依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
3. 在resources下面创建spring.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<bean class="com.ujiuye.bean.UserBean" id="u1"></bean>
<!--scope="prototype"多例 singleton单例-->
<bean class="com.ujiuye.bean.UserBean" name="u2,u3" scope="prototype"/>
</beans>
测试
@Test
public void t1(){
//之前创建对象
// UserBean u=new UserBean();
ApplicationContext app=new ClassPathXmlApplicationContext("spring.xml");
UserBean u= (UserBean) app.getBean("u3");
UserBean u2= (UserBean) app.getBean("u3");
System.out.println(u==u2);
}
依赖注入(DI)
给属性赋值:
1. 通过set方法赋值:
2. 通过构造方法赋值:
<bean class="com.ujiuye.bean.UserBean" id="u1"></bean>;
相当于写了 UserBean u1=new UserBean();
ref属性,指向当前属性依赖的另外一个对象
public class PersonBean {
private int pid;
private String pname;
private CardBean card;
public PersonBean(int pid, String pname) {
this.pid = pid;
this.pname = pname;
}
// alt+insert 生成get/set/toString
}
public class CardBean {
private int cid;
private String cnum;
}
Spring.xml
<bean class="com.ujiuye.bean.PersonBean" id="p1">
<!-- <constructor-arg name="pid" value="100"/>
<constructor-arg name="pname" value="admin"/>-->
<constructor-arg index="0" value="100"/>
<constructor-arg index="1" value="admin"/>
<!-- <property name="card">
<bean class="com.ujiuye.bean.CardBean">
<property name="cid" value="111"/>
<property name="cnum" value="110"/>
</bean>
</property>-->
<property name="card" ref="card"></property>
</bean>
<bean class="com.ujiuye.bean.CardBean" id="card">
<property name="cid" value="111"/>
<property name="cnum" value="110"/>
</bean>
测试:
@Test
public void t2(){
ApplicationContext app=new ClassPathXmlApplicationContext("spring.xml");
PersonBean p1= (PersonBean) app.getBean("p1");
System.out.println(p1);
}
3. springioc注入各种集合
- 实体类
public class CardBean {
private int cid;
private String cnum;
private List list;
private List<PersonBean> ps;
private Set set;
private Map map;
//alt+insert 生成get/set/toString
}
- Spring.xml配置
<bean class="com.ujiuye.bean.CardBean" id="card">
<property name="cid" value="111"/>
<property name="cnum" value="110"/>
<property name="list">
<list>
<value>1111</value>
<value>2222</value>
<value>3333</value>
</list>
</property>
<property name="set">
<set>
<value>aaa</value>
<value>aaa</value>
<value>bbb</value>
</set>
</property>
<property name="map">
<map>
<entry key="name">
<value>张三</value>
</entry>
<entry key="password">
<value>123456</value>
</entry>
</map>
</property>
<property name="ps">
<list>
<bean class="com.ujiuye.bean.PersonBean">
<constructor-arg name="pid" value="1"/>
<constructor-arg name="pname" value="aaa"/>
</bean>
<bean class="com.ujiuye.bean.PersonBean">
<constructor-arg name="pid" value="2"/>
<constructor-arg name="pname" value="bbb"/>
</bean>
<bean class="com.ujiuye.bean.PersonBean">
<constructor-arg name="pid" value="3"/>
<constructor-arg name="pname" value="cc"/>
</bean>
</list>
</property>
</bean>
- 测试
@Test
public void t3(){
ApplicationContext app=new ClassPathXmlApplicationContext("spring.xml");
CardBean p1= (CardBean) app.getBean("card");
System.out.println(p1);
}
Springioc对多态的支持
利用spring+springjdbc curd
1. Pom 坐标依赖
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<!--spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.0</version>
</dependency>
2. 书写PersonDao
public interface PersonDao {
int add(PersonBean p);
int del(int id);
int update(PersonBean p);
List<PersonBean> findAll();
}
3. personDaoImpl
public class PersonDaoImpl implements PersonDao {
//spring-jdbc 的工具类
private JdbcTemplate template;
public JdbcTemplate getTemplate() {
return template;
}
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
@Override
public int add(PersonBean p) {
String sql="insert person(pname)values(?)";
return template.update(sql,p.getPname());
}
@Override
public int del(int id) {
String sql="delete from person where pid=?";
return template.update(sql,id);
}
@Override
public int update(PersonBean p) {
String sql="update person set pname=? where pid=?";
return template.update(sql,p.getPname(),p.getPid());
}
@Override
public List<PersonBean> findAll() {
String sql="select* from person";
List<PersonBean> list = template.query(sql, new RowMapper<PersonBean>() {
@Override
public PersonBean mapRow(ResultSet resultSet, int i) throws SQLException {
PersonBean p=new PersonBean();
p.setPid(resultSet.getInt("pid"));
p.setPname(resultSet.getString("pname"));
return p;
}
});
return list;
}
}
public class PersonDaoImpl implements PersonDao {
//spring-jdbc 的工具类
private JdbcTemplate template;
public JdbcTemplate getTemplate() {
return template;
}
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
@Override
public int add(PersonBean p) {
String sql="insert person(pname)values(?)";
return template.update(sql,p.getPname());
}
@Override
public int del(int id) {
String sql="delete from person where pid=?";
return template.update(sql,id);
}
@Override
public int update(PersonBean p) {
String sql="update person set pname=? where pid=?";
return template.update(sql,p.getPname(),p.getPid());
}
@Override
public List<PersonBean> findAll() {
String sql="select* from person";
List<PersonBean> list = template.query(sql, new RowMapper<PersonBean>() {
@Override
public PersonBean mapRow(ResultSet resultSet, int i) throws SQLException {
PersonBean p=new PersonBean();
p.setPid(resultSet.getInt("pid"));
p.setPname(resultSet.getString("pname"));
return p;
}
});
return list;
}
}
4. PersonSerice
public class PersonSerice {
private PersonDao dao;
public PersonDao getDao() {
return dao;
}
public void setDao(PersonDao dao) {
this.dao = dao;
}
/**添加
* @param p
* @return
*/
public int add(PersonBean p){
return dao.add(p);
}
public int del(int id){
return dao.del(id);
}
public int update(PersonBean p){
return dao.update(p);
}
public List<PersonBean> findAll(){
return dao.findAll();
}
}
5. Spring.xml
<bean class="com.ujiuye.service.PersonSerice" id="personService">
<property name="dao" ref="personDao"/>
</bean>
<bean class="com.ujiuye.dao.PersonDaoImpl" id="personDao">
<property name="template" ref="template"/>
</bean>
<bean class="org.springframework.jdbc.core.JdbcTemplate" id="template">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="url" value="jdbc:mysql://localhost:3306/tt?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
</bean>
6. 测试
@Test
public void t1(){
ApplicationContext app=new ClassPathXmlApplicationContext("spring.xml");
PersonSerice serice= (PersonSerice) app.getBean("personService");
PersonBean p=new PersonBean(13,"zzzz");
// serice.add(p);
// serice.del(11);
// serice.update(p);
List<PersonBean> list = serice.findAll();
System.out.println(list);
}
springioc注解的使用
1. 常用的注解
Springboot 极力推崇使用注解的方式配置。 1.配置bean的注解,相当于我们在xml中写了 @Component ,@ Repository ,@Service @Controller 注解放在类名上。如果没有给id的名字,直接默认以类名的首字母小写作为bean的id 将来项目要分为三层架构:
- dao (data access object) 数据访问层 @ Repository
- Service 业务层 (通过调用dao层整合成一个完整的业务),@Service
- Controller 控制层(控制页面的跳转) @Controller
- 如果有一层不好归纳与三层架构的任何一层,我们直接@Component
@Value 放在属性名上的,相当于在
@Autowired 注入,相当于在xml配置引用,可以自动从容器中寻找对应的类型,自动注入,而且可以省略get/set方法
@Resouce 和@AutoWired作用相同,但是他是jdk的注解 @Resouce(name= “id名”)
2. 案例1
1.改造personbean和cardBean
@Component("pp")
@Scope("prototype") //设置是否单例
public class PersonBean {
@Value("100")
private int pid;
@Value("张三")
private String pname;
@Autowired
private CardBean card;
}
2.spring_annotation.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
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">
<!--扫描注解-->
<context:component-scan base-package="com.ujiuye.bean"/>
</beans>
3. 单元测试
@Test
public void t1(){
ApplicationContext app=new ClassPathXmlApplicationContext("spring_annotation.xml");
PersonBean p= (PersonBean) app.getBean("pp"); //alt+enter 直接强转
PersonBean p2= (PersonBean) app.getBean("pp");
System.out.println(p);
System.out.println(p==p2);
}
改造上午 spring-jdbc 使用注解
1. 导入spring-test
<!--spring-test-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
2. 改造dao层接口的实现类
3. 改造UserService
4. 利用spring-test
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml"})
public class SpringTest {
@Autowired
private PersonSerice serice;
@Test
public void t1(){
List<PersonBean> list = serice.findAll();
System.out.println(list);
}
}
5. Spring.xml改造
Spring整合mybatis
1. Pom坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<!--druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.0</version>
</dependency>
<!--spring-test-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--mybatis-spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
</dependencies>
2. 创建PersonBean
public class PersonBean {
private int pid;
private String pname;
}
3. 创建PersonDao接口
public interface PersonDao {
int add(PersonBean p);
int del(int id);
int update(PersonBean p);
List<PersonBean> findAll();
}
4. 创建PersonService
@Service
public class PersonService {
@Autowired
private PersonDao dao;
/**添加
* @param p
* @return 成功/失败
*/
public boolean add(PersonBean p){
return dao.add(p)>0?true:false;
}
public boolean del(int id){
return dao.del(id)>0?true:false;
}
public boolean update(PersonBean p){
return dao.update(p)>0?true:false;
}
public List<PersonBean> findAll(){
return dao.findAll();
}
}
5. Mybatis_conf.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>
</configuration>
6. PersonMapper.xml
<?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.ujiuye.dao.PersonDao">
<insert id="add" parameterType="com.ujiuye.bean.PersonBean">
insert into person (pname) values (#{pname});
</insert>
<delete id="del">
delete from person where pid=#{0}
</delete>
<update id="update" parameterType="com.ujiuye.bean.PersonBean">
update person set pname=#{pname} where pid=#{pid}
</update>
<select id="findAll" resultType="com.ujiuye.bean.PersonBean">
select * from person
</select>
</mapper>
7. Spring.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
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">
<!--包扫描-->
<context:component-scan base-package="com.ujiuye"/>
<!--配置数据源-->
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="url" value="jdbc:mysql://localhost:3306/tt?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
</bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!--配置数据源-->
<property name="dataSource" ref="dataSource"/>
<!--配置mybatis的核心配置文件-->
<property name="configLocation" value="classpath:mybatis/mybatis_conf.xml"/>
<!--配置mapper.xml文件-->
<property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"/>
</bean>
<!--配置dao层接口-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ujiuye.dao"/>
</bean>
</beans>
8. 单元测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring.xml")
public class Spring_MybatisTest {
@Autowired
private PersonService service;
@Test
public void t1(){
PersonBean p=new PersonBean();
p.setPname("xyz");
p.setPid(13);
// boolean success = service.add(p);
// boolean success = service.del(14);
/* boolean success = service.update(p);
System.out.println(success);*/
List<PersonBean> list = service.findAll();
System.out.println(list);
}
}