1.如果你的英语足够好可以去看spring的官网。
2.简单介绍spring
①开源轻量级框架,说白了就是简化开发
②核心部分:AOP切面编程:我理解的就是在不改变已有代码的情况下去扩展一些功能。
IOC控制反转:还记得刚学程序的时候么,是private Student stu=new Student();这么干的。ioc就是把这个过程 交给spring容器来处理。所以叫做控制反转。
DI依赖注入:这个是基于IOC的,也就是先交给spring管理,然后通过spring给属性注入值。
③spring在javaweb的三层结构中都有相应的解决方案。
web层 springMVC
service层 IOC
dao层 jdbcTemplate(一般会被Hibernate、Mybatis代替)
3.导入jar包
①去官网下载
下载并解压你会看到libs文件夹下的jar包有这样的特点
spring-aop-5.0.5.RELEASE.jar这个是我们要用的jar包
spring-aop-5.0.5.RELEASE-sources.jar这个是源码
②如果用spring的基本功能,导入4个核心的jar包就可以了。
spring-context-5.0.5.RELEASE-javadoc.jar
spring-core-5.0.5.RELEASE.jar
spring-expression-5.0.5.RELEASE.jar
spring-beans-5.0.5.RELEASE.jar
另外还需要加入commons-logging-1.1.3.jar、log4j-1.2.11.jar两个日志的jar包,不然会出现下面异常:
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
③创建spring核心配置文件:
(1)spring核心配置文件名称和位置不是固定的,建议放到src下面,官方建议applicationContext.xml
(2)引入schema约束
spring-framework-5.0.5.RELEASE/docs/spring-framework-reference/core.html
从官方下载的spring版本中找到docs->spring-framework-reference->core.html(中可以找到相关schema约束)
如图:
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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="user" class="test1.User" ></bean> </beans>
User类:
public class User { public void show(){ System.out.println("我是User"); } }
测试类:
public class MainTest { public static void main(String[] args){ //1.加载xml文件 ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); //2.拿到user对象,这里user是bean里面的id User user = (User)context.getBean("user"); user.show(); } }
运行结果:
经过上面的步骤,最简单的通过配置bean的方式来管理对象就成功了。下面详细总结一下。
spring管理bean方式(IOC):
①xml配置方式(xml方式)
②注解方式(用的最多)(注解方式)
spring属性注入方式(DI):
①set方法注入(重点)(xml方式)
②有参构造方法注入(xml方式)
③注解注入(用的比较多)(注解方式)
4.介绍Spring管理bean(xml方式)
(1)先来介绍bean标签属性
id:唯一标识,不能包含特殊字符。
name:跟id作用一样,但是可以包含特殊字符。
class:指定类的路径。
scope(范围):singleton单例 ,prototype(多例)
(2)bean实例化的三种方式:
①使用类的无参构造函数(重点)
注意User类的变化,编写一个有参构造方法(此时不再有无参构造函数):
下面再运行会报异常:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'user' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [test1.User]: No default constructor found; nested exception is java.lang.NoSuchMethodException: test1.User.<init>()
下面我手动再写一个无参构造函数,如下:
再来看运行结果,运行成功:
说明默认使用无参构造函数来实例化的。
②使用静态工厂实例化(创建静态方法,返回类的对象)
注意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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- <bean id="user" class="test1.User" ></bean>--> <bean id="user" class="test1.BeanFactory" factory-method="getUser" ></bean> </beans>
创建静态工厂类BeanStaticFactory(注意里面的方法是 static的):
运行测试类MainText:
③使用实例工厂创建(创建非静态方法,返回类的对象)
注意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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- <bean id="user" class="test1.User" ></bean>--> <!--<bean id="user" class="test1.BeanStaticFactory" factory-method="getUser" ></bean>--> <bean id="beanCommonFactory" class="test1.BeanCommonFactory" ></bean> <bean id="user" factory-bean="beanCommonFactory" factory-method="getUser"></bean> </beans>
创建普通工厂BeanCommonFactory
运行测试类MainText:
(3)属性注入
一.使用有参构造函数注入属性
User类
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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="user" class="test1.User" > <constructor-arg name="userName" value="小明"></constructor-arg> </bean> <!--<bean id="user" class="test1.BeanStaticFactory" factory-method="getUser" ></bean>--> <!--<bean id="beanCommonFactory" class="test1.BeanCommonFactory" ></bean> <bean id="user" factory-bean="beanCommonFactory" factory-method="getUser"></bean>--> </beans>
运行测试类MainTest结果:
二.使用set方法注入(重点)
User类:
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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="user" class="test1.User" > <property name="userName" value="小明"></property> </bean> <!--<bean id="user" class="test1.BeanStaticFactory" factory-method="getUser" ></bean>--> <!--<bean id="beanCommonFactory" class="test1.BeanCommonFactory" ></bean> <bean id="user" factory-bean="beanCommonFactory" factory-method="getUser"></bean>--> </beans>
运行测试类MainText结果如下:
①注入对象类型:
注意applicationContext.xml变化
创建UserDao类:
创建UserService类:
修改MainTest类:
运行测试结果:
②注入复杂类型
数组、List集合、Map集合、Properties
修改UserService类:
public class UserService { private UserDao userDao; private Integer[] array; private List<String> list; private Map<String,String> map; private Properties properties; public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } public Integer[] getArray() { return array; } public void setArray(Integer[] array) { this.array = array; } public List<String> getList() { return list; } public void setList(List<String> list) { this.list = list; } public Map<String, String> getMap() { return map; } public void setMap(Map<String, String> map) { this.map = map; } public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } }
修改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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userDao" class="test2.UserDao"></bean> <bean id="userService" class="test2.UserService"> <property name="userDao" ref = "userDao"></property> <property name="array"> <list> <value>1</value> <value>2</value> <value>3</value> </list> </property> <property name="list"> <list> <value>小明1</value> <value>小明2</value> <value>小明3</value> </list> </property> <property name="map"> <map> <entry key="a" value="A"></entry> <entry key="b" value="B"></entry> <entry key="c" value="C"></entry> </map> </property> <property name="properties"> <props> <prop key="userName">test</prop> <prop key="password">123456</prop> </props> </property> </bean> </beans>
修改MainTest类
public class MainTest { public static void main(String[] args){ //1.加载xml文件 ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); //2.拿到user对象,这里user是bean里面的id //User user = (User)context.getBean("user"); UserService userService = (UserService)context.getBean("userService"); UserDao userDao=null; Integer[] array=null; List<String> list=null; Map<String,String> map=null; Properties properties=null; if(userService!=null){ userDao=userService.getUserDao(); array=userService.getArray(); list=userService.getList(); map=userService.getMap(); properties=userService.getProperties(); } if(array!=null){ for(int i=0;i<array.length;i++){ System.out.println(array[i]); } } if(list!=null&&list.size()>0){ for (String s:list){ System.out.println(s); } } if(map!=null){ for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); } } if(properties!=null){ for (Map.Entry<Object, Object> entry : properties.entrySet()) { System.out.println(entry.getKey() + "=" + entry.getValue()); } } } }
运行结果:
5.Spring管理Bean(注解方式)
注解就是给类打上标记,这样spring才能识别管理
注解可以打在类上,也可以打在属性上
一:使用注解来创建对象
打在类上的注解:
@Controller(习惯放在web层)
@Service(习惯放在业务层)
@Repository(习惯放在持久层)
@Component
目前这四个注解的功能是一样的,都是放在类上用来创建对象。
需要再引入spring-aop-5.0.5.RELEASE.jar jar包
修改applicationContext.xml(多了spring-context.xsd schema约束,在联网的情况下输入<context:component-scan base-package="test1,test2"></context:component-scan>会自动添加约束)
修改User类:(@Component(value="user") 这里user相当于bean里面的id,可以省略value值)
MainText类:
public class MainTest { public static void main(String[] args){ //1.加载xml文件 ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); //2.拿到user对象,这里user是bean里面的id User user = (User)context.getBean("user"); user.show(); } }
运行结果(省略)
spring通过@Scope(value="prototype")实现多例,spring默认生成的对象是单例的
如下:
@Component(value = "user") @Scope(value = "prototype") public class User { private String userName; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public void show(){ System.out.println("我是User"); System.out.println("我的userName属性值:"+this.userName); } }
MianTest测试:
public class MainTest { public static void main(String[] args){ //1.加载xml文件 ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); //2.拿到user对象,这里user是bean里面的id User user1 = (User)context.getBean("user"); User user2 = (User)context.getBean("user"); // user.show(); System.out.print(user1==user2); } }
运行结果:
二:使用注解来注入属性
@Autowired (按类型装配)
@Resource(按名称装配)
关于这两个注解的区别大家可以去网上找些资料,关于他们的资料很多
直接上代码:
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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--可以扫描包下面的 类、属性、方法上的注解--> <context:component-scan base-package="test1,test2"></context:component-scan> </beans>
UserDao类:
@Repository public class UserDao { public void show(){ System.out.println("我是UserDao"); } }
UserService类:(这里用的是@Autowired注解,关于@Resource注解,下去可以自己试试)
@Service public class UserService { @Autowired private UserDao userDao; public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } }
测试MainText类:
public class MainTest { public static void main(String[] args){ //1.加载xml文件 ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); //2.拿到user对象,这里user是bean里面的id UserService userService = (UserService)context.getBean("userService"); UserDao userDao=userService.getUserDao(); if(userDao!=null){ userDao.show(); } } }
运行结果省略。