1.三层架构
1.mvc模式
mvc: web开发中,使用mvc架构模式。m: 数据,V: 视图,C: 控制器。
m数据: 来自数据库mysq|, 来自文件,来自网络
C控制器: 接收请求,调用service对象, 显示请求的处理结果。当前使用servlet作为控制器
v视图: 现在使用jsp,html, CSS, js。显示请求的处理结果, 把m中数据显示出来。
2.三层架构
1.界面层(视图层) :接收用户的请求,调用service, 显示请求的处理结果的。包含了jsp, html, servlet等对象。对应的包controller
2.业务逻辑层:处理业务逻辑,使用算法处理数据的。把数据返回给界面层。对应的是servic包, 和包中的很多的XXXService类。例如: StudentService ,OrderService, ShopService
3.持久层(数据库访问层) :访问数据库,或者读取文件,访问网络。获取数据。对应的包是dao。 dao包中很多的StudentDao, OrderDao, ShopDao等等。
3.代码示例
持久层
持久层接口
/**
* 持久层接口
*/
public interface IUserDao {
void saveUser();
}
实现持久层接口
/**
* 实现持久层接口
*/
public class IUserDaoImpl implements IUserDao {
public void saveUser() {
System.out.println("用户保持了");
}
}
业务层
业务层接口
/**
* 业务层接口
*/
public interface IUservice {
void SaveAccount() ;
}
业务层接口实现
/**
* 实现业务层接口
*/
public class IUserviceImpl implements IUservice {
private IUserDao iUserDao;
/**
* 调用持久层接口的方法
*/
public void SaveAccount() {
//多态创建
iUserDao = new IUserDaoImpl();
//调用持久层接口方法
iUserDao.saveUser();
}
}
表现层
/**
* 模拟表现层,调用业务层
*/
public class Client {
public static void main(String[] args) {
new IUserviceImpl().saveUser();
}
}
业务逻辑
表现层------(调用)—>业务层------(调用)----->持久层
2.程序耦合
1.程序耦合概述
什么是耦合?耦合就是程序之间的依赖关系,耦合程度高,相互依赖程度高,耦合程度低,相互依赖程度低。
一个程序来说,应当程序相互依赖程度越低越好。
从上面的代码中可以发现代码之间的依赖程度很高
假设IUserviceImpl有错误,IUserviceImpl有错误,那么后面的程序都会有错误。
2.解耦
new创建对象
工厂模式创建对象
工厂模式的具体实现
步骤一:建立一个properties文件,保持我们想要加载类的全限定类名称
步骤二:建立工厂类
public class BeanFactory {
private static Map<String,Object> beans;
private static Properties prop;
static {
try {
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
prop = new Properties();
prop.load(in);
beans = new HashMap<String, Object>();
Enumeration<Object> keys = prop.keys();
while (keys.hasMoreElements()) {
//取出每个Key
String key = keys.nextElement().toString();
System.out.println(key);
//根据key获取value
String beanPath = prop.getProperty(key);
System.out.println(beanPath);
//反射创建对象
Object value = Class.forName(beanPath).newInstance();
//把key和value存入容器中
beans.put(key, value);
}
} catch (Exception e){
throw new ExceptionInInitializerError("初始化properties失败!");
}
}
public static Object getBean(String beanName) throws Exception{
return beans.get(beanName);
}
}
步骤三:使用工厂创建对象
业务层调用持久层使用
public class IAserviceImpl implements IAservice {
public void SaveAccount() throws Exception {
IAccountDaoimpl accountDao =(IAccountDaoimpl) BeanFactory.getBean("Dao");
accountDao.SaveAccount();
}
}
表现层调用业务层使用
public class Client {
public static void main(String[] args) throws Exception {
IAserviceImpl iAserviceImpl =(IAserviceImpl)BeanFactory.getBean("Service");
iAserviceImpl.SaveAccount();
}
}
代码分析
3.bean对象
什么是bean:Bean:在计算机英语中,有可重用组件的含义
JavaBean:用java语言编写的可重用组件
bean:是任意实例化对象与其名称相对应的对象(也称组件)
beans容器
是储存对象的容器(对象名称1,实例化对象1),(对象名称2,实例化对象2)…如下图所示
如何才能获得这么一个容器呢?
需要告诉Spring框架:这个类的全限定类名称,以及我们给这个类实例化对象取的名字
3.使用spring的IOC解决程序耦合
1.配置依赖
在项目pom.xml文件中配置如下Spring依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
</dependencies>
2.添加bean.xml配置文件
bean.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="Dao" class="it.cast.dao.impl.IAccountDaoimpl"></bean>
<bean id="Service" class="it.cast.service.impl.IAserviceImpl"></bean>
</beans>
3.使用配置
业务层调用持久层使用
public class IAserviceImpl implements IAservice {
public void SaveAccount() throws Exception {
//1.获取核心容器对象
ApplicationContext container= new ClassPathXmlApplicationContext("bean.xml");
//2.取出对象
IAccountDaoimpl dao =(IAccountDaoimpl) container.getBean("Dao");
dao.SaveAccount();
}
}
表现层调用业务层使用
public class Client {
public static void main(String[] args) throws Exception {
//1.获取核心容器对象
ApplicationContext container= new ClassPathXmlApplicationContext("bean.xml");
//2.取出对象
IAserviceImpl service =(IAserviceImpl) container.getBean("Service");
//3.调用方法
service.SaveAccount();
}
}
4.IOC核心容器
ApplicationContext核心容器接口
ApplicationContext
:它在构建核心容器时,创建对象采取的策略是采用立即加载的方式。也就是说,只要一读取完配置文件马上就创建配置文件中配置的对象。单例对象适用。
ApplicationContext的三个常用实现类
ClassPathXmlApplicationContext
:它可以加载类路径下的配置文件,要求配置文件必须在类路径下。不在的话,加载不了。(更常用)FileSystemXmlApplicationContext
:它可以加载磁盘任意路径下的配置文件(必须有访问权限)AnnotationConfigApplicationContext
:它是用于读取注解创建容器的
BeanFactory核心容器接口
BeanFactory
:它在构建核心容器时,创建对象采取的策略是采用延迟加载的方式。也就是说,什么时候根据id获取对象了,什么时候才真正的创建对象。多例对象适用。
5.bean标签配置(xml配置文件)
创建bean的三种方式
第一种方式:使用默认构造函数创建
<bean id="Dao" class="it.cast.dao.impl.IAccountDaoimpl"></bean>
<bean id="Service" class="it.cast.service.impl.IAserviceImpl"></bean>
在spring的配置文件中使用bean标签,配以id和class属性之后,且没有其他属性和标签时。采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建。
测试:我们在默认构造函数添加一句话看能不能调用出来
很明显,是采用了默认构造函数调用的
第二种方式:使用工厂中的静态方法创建对象(使用某个类中的静态方法创建对象,并存入spring容器)
模拟一个静态工厂,创建持久层实现类
public class RetuenIAccountDaoimpl {
//必须是静态
public static IAccountDaoimpl getIAccountDaoimpl(){
return new IAccountDaoimpl();
}
}
bean标签
<bean id="Dao" class="it.cast.dao.impl.RetuenIAccountDaoimpl" factory-method="getIAccountDaoimpl"></bean>
使用 RetuenIAccountDaoimpl类中的静态方法 getIAccountDaoimpl创
建对象,并存入spring容器
id 属性:指定 bean的id,用于从容器中获取
class属性:指定静态工厂的全限定类名
factory-method属性:指定生产对象的静态方法
第三种方式:spring管理实例工厂—使用实例工厂的方法创建对象
模拟一个工厂,创建持久层实现类
public class RetuenIAccountDaoimpl {
public IAccountDaoimpl getIAccountDaoimpl(){
return new IAccountDaoimpl();
}
}
xml标签
<bean id="Dao" class="it.cast.dao.impl.RetuenIAccountDaoimpl"></bean>
<bean id="factory" factory-bean="Dao" factory-method="getIAccountDaoimpl"></bean>
详细解析
先把工厂的创建交给 spring 来管理。然后在使用工厂的 bean 来调用里面的方法
factory-bean 属性:用于指定实例工厂 bean 的 id。
factory-method 属性:用于指定实例工厂中创建对象的方法。
bean的作用范围调整
作用:
- 用于配置对象让 spring 来创建的。
- 默认情况下它调用的是类中的无参构造函数。如果没有无参构造函数则不能创建成功。
属性:
id:给对象在容器中提供一个唯一标识。用于获取对象。
class:指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数。
scope:指定对象的作用范围。(下面是取值的类型)
-
singleton :默认值,单例的.
-
prototype :多例的.
-
request :WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 request 域中.
-
session :WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 session 域中.
-
global session :WEB 项目中,应用在 Portlet 环境.如果没有 Portlet 环境那么globalSession 相当于 session.
bean对象的生命周期
单例对象:scope=“singleton”
一个应用只有一个对象的实例。它的作用范围就是整个引用。
生命周期:
- 对象出生:当应用加载,创建容器时,对象就被创建了。
- 对象活着:只要容器在,对象一直活着。
- 对象死亡:当应用卸载,销毁容器时,对象就被销毁了。
多例对象:scope=“prototype”
每次访问对象时,都会重新创建对象实例。
生命周期:
- 对象出生:当使用对象时,创建新的对象实例。
- 对象活着:只要对象在使用中,就一直活着。
- 对象死亡:当对象长时间不用时,被 java 的垃圾回收器回收了。
4.spring的依赖注入(XML)
什么是依赖注入:就是创建对象时,如果需要一定的参数,通过Spring标签的配置,传递参数给创建的对象,让其成功创建对象。
依赖注入:
能注入的数据:有三类
基本类型和String
其他bean类型(在配置文件中或者注解配置过的bean)
复杂类型/集合类型
1.构造函数注入
顾名思义,就是使用类中的构造函数,给成员变量赋值。注意,赋值的操作不是我们自己做的,而是通过配置的方式,让 spring 框架来为我们注入。
需要创建的对象
public class service {
private String name;
private Integer id;
private Date birthday;
// 复写构造方法,没有无参构造方法
public service(String name, Integer id, Date birthday) {
this.name = name;
this.id = id;
this.birthday = birthday;
}
@Override
public String toString() {
return "service{" +
"name='" + name + '\'' +
", id=" + id +
", birthday=" + birthday +
'}';
}
}
从上面的代码可以知道,创建serivce对象时,必须传递 name ,id,birthday 参数
bean标签
<bean id="service" class="it.core.service.service">
<constructor-arg name="id" value="18"></constructor-arg>
<constructor-arg name="name" value="老王"></constructor-arg>
<constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>
<bean id="now" class="java.util.Date"></bean>
xml分析
使用的标签:constructor-arg
标签出现的位置:bean标签的内部
标签中的属性
-
type
:用于指定要注入的数据的数据类型,该数据类型也是构造函数中某个或某些参数的类型 -
index
:用于指定要注入的数据给构造函数中指定索引位置的参数赋值。索引的位置是从0开始 -
name
:用于指定给构造函数中指定名称的参数赋值(常用的)
以上三个用于指定给构造函数中哪个参数赋值
-
value
:用于提供基本类型和String类型的数据 -
ref
:用于指定其他的bean类型数据。它指的就是在spring的Ioc核心容器中出现过的bean对象
测试结果
2.set方法注入
顾名思义,就是在类中提供需要注入成员的 set 方法。
需要创建的对象
public class service {
private String name;
private Integer id;
private Date birthday;
public void setName(String name) {
this.name = name;
}
public void setId(Integer id) {
this.id = id;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "service{" +
"name='" + name + '\'' +
", id=" + id +
", birthday=" + birthday +
'}';
}
}
bean标签
<bean id="service" class="it.core.service.service">
<property name="name" value="小明"></property>
<property name="id" value="21"></property>
<property name="birthday" ref="now"></property>
</bean>
<bean id="now" class="java.util.Date"></bean>
必须要保证setXxxx与name的xxxx一致
涉及的标签:property
出现的位置:bean标签的内部
标签的属性
name
:用于指定注入时所调用的set方法名称value
:用于提供基本类型和String类型的数据ref
:用于指定其他的bean类型数据。它指的就是在spring的Ioc核心容器中出现过的bean对象
测试结果
3.使用p名称空间注入数据
在bean标签添加如下
bean标签
<bean id="accountService"
class="it.core.service" p:name="test" p:age="21" p:birthday-ref="now"/>
</beans>
4.注入集合属性
public class service01 {
private String[] myStrs;
private List<String> myList;
private Set<String> mySet;
private Map<String,String> myMap;
private Properties myProps;
public void method(){
System.out.println(Arrays.toString(myStrs));
System.out.println(myList);
System.out.println(mySet);
System.out.println(myMap);
System.out.println(myProps);
}
public String[] getMyStrs() {
return myStrs;
}
public void setMyStrs(String[] myStrs) {
this.myStrs = myStrs;
}
public List<String> getMyList() {
return myList;
}
public void setMyList(List<String> myList) {
this.myList = myList;
}
public Set<String> getMySet() {
return mySet;
}
public void setMySet(Set<String> mySet) {
this.mySet = mySet;
}
public Map<String, String> getMyMap() {
return myMap;
}
public void setMyMap(Map<String, String> myMap) {
this.myMap = myMap;
}
public Properties getMyProps() {
return myProps;
}
public void setMyProps(Properties myProps) {
this.myProps = myProps;
}
}
bean标签
<bean id="service01" class="it.core.service.service01">
<property name="myStrs">
<array>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</array>
</property>
<property name="mySet">
<set>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</set>
</property>
<property name="myList">
<list>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</list>
</property>
<property name="myMap">
<map>
<entry key="testA" value="AAA"></entry>
<entry key="testB" value="BBB"></entry>
<entry key="testC" value="CCC"></entry>
</map>
</property>
<property name="myProps">
<props>
<prop key="testA">AAA</prop>
<prop key="testB">BBB</prop>
<prop key="testC">CCC</prop>
</props>
</property>
</bean>
测试结果
拓展内容
-
用于给List结构集合注入的标签: list array set
-
用于个Map结构集合注入的标签::map props
结构相同,标签可以互换
bean标签
<bean id="service01" class="it.core.service.service01">
<property name="myStrs">
<list>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</list>
</property>
<property name="mySet">
<list>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</list>
</property>
<property name="myList">
<list>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</list>
</property>
<property name="myMap">
<props>
<prop key="testA">AAA</prop>
<prop key="testB">BBB</prop>
<prop key="testC">CCC</prop>
</props>
</property>
<property name="myProps">
<props>
<prop key="testA">AAA</prop>
<prop key="testB">BBB</prop>
<prop key="testC">CCC</prop>
</props>
</property>
</bean>
任然可以保存进去
5.Spring的依赖注入(注解)
1.声明扫描注解
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">
<!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为
context名称空间和约束中-->
<context:component-scan base-package="it.rose"></context:component-scan>
</beans>
关键是这一段
2.用于创建对象的注解
他们的作用就和在XML配置文件中编写一个< bean >标签实现的功能是一样的
Component
作用:用于把当前类对象存入spring容器中
属性:
- value:用于指定bean的id。当我们不写时,它的默认值是当前类名,且首字母改小写。
注意:当类的名字是以两个或以上的大写字母开头的话,bean的名字会与类名保持一致
以下三个注解他们的作用和属性与Component是一模一样。
他们三个是spring框架为我们提供明确的三层使用的注解,使我们的三层对象更加清晰
Controller:一般用在表现层
Service:一般用在业务层
Repository:一般用在持久层
默认的
@Component
public class service {
public void method01(){
System.out.println("这是方法01");
}
}
自己取名字的
@Component("se")
public class service {
public void method01(){
System.out.println("这是方法01");
}
}
调用bean对象
public class Client {
public static void main(String[] args) {
ApplicationContext as=new ClassPathXmlApplicationContext("bean01.xml");
service se = as.getBean("se",service.class);
se.method01();
}
}
3.用于注入数据的
他们的作用就和在xml配置文件中的bean标签中写一个标签的作用是一样的
1.Autowired注解
作用:从容器找到与要注入的变量类型匹配类型,注入进去
代码分析
1.如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错。
2.如果IOC(beans容器)容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功,就像上面的情况一样
3.如果Ioc容器中有多个类型匹配时:就要使用另一个标签Qualifier标签
- 作用:在按照类中注入的基础之上再按照名称注入。它在给类成员注入时不能单独使用
- 属性:value:用于指定注入bean的id。
简而言之:
IOC容器中没有一个对应类型的bean对象时,报错
IOC容器有唯一一个与之对应类型的bean对象时,直接注入(配对)
IOC容器有许多个与之对应类型的bean对象时,我们就要通过Qualifier标签,来配置我们想要找的bean对象的名字
2.Resource注解
相当于上面两个标签的结合体
导入Resource标签的依赖
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现。另外,集合类型的注入只能通过XML来实现。
3.Value注解
作用:用于注入基本类型和String类型的数据
属性:
- value:用于指定数据的值。它可以使用spring中SpEL(也就是spring的el表达式)
- SpEL的写法:${表达式}
4.用于改变作用范围的
他们的作用就和在bean标签中使用scope属性实现的功能是一样的
1.Scope 注解
作用:用于指定bean的作用范围
属性:
- value:指定范围的取值。常用取值:singleton prototype
5.生命周期相关(了解)
他们的作用就和在bean标签中使用init-method和destroy-methode的作用是一样的
1.PreDestroy 作用:用于指定销毁方法
2.PostConstruct 作用:用于指定初始化方法