本文共 10410 字,大约阅读时间需要 34 分钟。
目录
spring 的优势
程序的耦合及解耦
bean.propertiesaccountService=com.itheima.service.impl.AccountServiceImplaccountDao=com.itheima.dao.impl.AccountDaoImplBeanfactory
/** * 一个创建Bean对象的工厂 * * Bean:在计算机英语中,有可重用组件的含义。 * JavaBean:用java语言编写的可重用组件。 * javabean > 实体类 * * 它就是创建我们的service和dao对象的。 * * 第一个:需要一个配置文件来配置我们的service和dao * 配置的内容:唯一标识=全限定类名(key=value) * 第二个:通过读取配置文件中配置的内容,反射创建对象 * * 我的配置文件可以是xml也可以是properties */public class BeanFactory { //定义一个Properties对象 private static Properties props; //定义一个Map,用于存放我们要创建的对象。我们把它称之为容器 private static Mapbeans; //使用静态代码块为Properties对象赋值 static { try { //实例化对象 props = new Properties(); //获取properties文件的流对象 InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"); props.load(in); //实例化容器 beans = new HashMap (); //取出配置文件中所有的Key Enumeration keys = props.keys(); //遍历枚举 while (keys.hasMoreElements()){ //取出每个Key String key = keys.nextElement().toString(); //根据key获取value String beanPath = props.getProperty(key); //反射创建对象 Object value = Class.forName(beanPath).newInstance(); //把key和value存入容器中 beans.put(key,value); } }catch(Exception e){ throw new ExceptionInInitializerError("初始化properties失败!"); } } /** * 根据bean的名称获取对象 * @param beanName * @return */ public static Object getBean(String beanName){ return beans.get(beanName); } /** * 根据Bean的名称获取bean对象 * @param beanName * @return public static Object getBean(String beanName){ Object bean = null; try { String beanPath = props.getProperty(beanName);// System.out.println(beanPath); bean = Class.forName(beanPath).newInstance();//每次都会调用默认构造函数创建对象 }catch (Exception e){ e.printStackTrace(); } return bean; }*/} Client
/** * 模拟一个表现层,用于调用业务层 */public class Client { public static void main(String[] args) { //IAccountService as = new AccountServiceImpl(); for(int i=0;i<5;i++) { IAccountService as = (IAccountService) BeanFactory.getBean("accountService"); System.out.println(as); as.saveAccount(); } }}IAccountService(I开头的为接口)
/** * 账户业务层的接口 */public interface IAccountService { /** * 模拟保存账户 */ void saveAccount();}AccountServiceImp
/** * 账户的业务层实现类 */public class AccountServiceImpl implements IAccountService {// private IAccountDao accountDao = new AccountDaoImpl(); private IAccountDao accountDao = (IAccountDao)BeanFactory.getBean("accountDao");// private int i = 1; public void saveAccount(){ int i = 1; accountDao.saveAccount(); System.out.println(i); i++; }}
IOC概念和spring中的IOC
ioc的概念图
spring中的ioc
前期准备
官网: http://spring.io/下载地址:http://repo.springsource.org/libs-release-local/org/springframework/spring解压 :(Spring 目录结构 :)* docs :API 和开发规范* libs :jar 包和源码* schema :约束特别说明:spring5 版本是用 jdk8 编写的,所以要求我们的 jdk 版本是 8 及以上同时 tomcat 的版本要求 8.5 及以上
/*** 账户的业务层接口* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/public interface IAccountService {/*** 保存账户(此处只是模拟,并不是真的要保存)*/void saveAccount();}/*** 账户的业务层实现类* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/public class AccountServiceImpl implements IAccountService {private IAccountDao accountDao = new AccountDaoImpl();//此处的依赖关系有待解决@Overridepublic void saveAccount() {accountDao.saveAccount();}}
/*** 账户的持久层接口* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/public interface IAccountDao {/*** 保存账户*/void saveAccount();}/*** 账户的持久层实现类* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/public class AccountDaoImpl implements IAccountDao {@Overridepublic void saveAccount() {System.out.println("保存了账户");}}
基于 XML 的配置
/spring-framework-5.0.2.RELEASE/docs/spring-framework-reference/html5/core.html
/*** 模拟一个表现层* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/public class Client {/** * 使用 main 方法获取容器测试执行*/public static void main(String[] args) {//1.使用 ApplicationContext 接口,就是在获取 spring 容器ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");//2.根据 bean 的 id 获取对象IAccountService aService = (IAccountService) ac.getBean("accountService");System.out.println(aService);IAccountDao aDao = (IAccountDao) ac.getBean("accountDao");System.out.println(aDao);}}
Spring 基于 XML 的 IOC 细节
BeanFactory 才是 Spring 容器中的顶层接口ApplicationContext 是它的子接口 (使用多一点)BeanFactory 和 ApplicationContext 的区别: 创建对象的时间点不一样ApplicationContext :只要一读取配置文件,默认情况下就会创建对象 (单例对象适用)BeanFactory :什么使用什么时候创建对象 (多例对象适用)
ClassPathXmlApplicationContext : 它是从类的根路径下加载配置文件 则推荐使用这种FileSystemXmlApplicationContext : 它是从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置AnnotationConfigApplicationContext : 当我们使用注解配置容器对象时,需要使用此类来创建 spring 容器。它用来读取注解
作用:用于配置对象让 spring 来创建的默认情况下 它调用的是类中的无参构造函数。如果没有无参构造函数则不能创建成功属性:id :给对象在容器中提供一个唯一标识。用于获取对象class :指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数scope :指定对象的作用范围。* singleton : 默认值,单例的* prototype : 多例的* request :WEB项目中的请求范围 ,Spring 创建一个 Bean 的对象 , 将对象存入到 request 域中* session :WEB项目中的会话范围 ,Spring 创建一个 Bean 的对象 , 将对象存入到 session 域中* global session :WEB 项目中 , 应用在 Portlet 环境(集群环境) . 如果没有 Portlet 环境那么 globalSession 相当于 sessioninit-method :指定类中的初始化方法名称destroy-method :指定类中销毁方法名称
单例对象: scope="singleton"一个应用只有一个对象的实例。它的作用范围就是整个引用生命周期:对象出生:当应用加载,创建容器时,对象就被创建了对象活着:只要容器在,对象一直活着对象死亡:当应用卸载,销毁容器时,对象就被销毁了多例对象: scope="prototype"每次访问对象时,都会重新创建对象实例生命周期:对象出生:当使用对象时,创建新的对象实例对象活着:只要对象在使用中,就一直活着对象死亡:当对象长时间不用时,被 java 的垃圾回收器回收了
第一种方式:使用默认无参构造函数
在spring的配置文件使用bean标签,配以id和class属性之后,且没有其他属性和标签
采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则无法创建
/*** 模拟一个静态工厂,创建业务层实现类*/public class StaticFactory {public static IAccountService createAccountService(){return new AccountServiceImpl();}}
* 模拟一个实例工厂,创建业务层实现类* 此工厂创建对象,必须现有工厂实例对象,再调用方法*/public class InstanceFactory {public IAccountService createAccountService(){return new AccountServiceImpl();}}
依赖注入(Dependency Injection)
能注入的数据类型基本类型和String其他bean类型(在配置文件中或者注解配置过的bean)复杂类型/集合类型注入方式使用构造函数提供使用set方法提供使用注解提供
顾名思义,就是使用类中的构造函数,给成员变量赋值。注意,赋值的操作不是我们自己做的,而是通过配置 的方式,让 spring 框架来为我们注入
<!-- 使用构造函数的方式,给 service 中的属性传值 要求: 类中需要提供一个对应参数列表的构造函数。 涉及的标签:
constructor-arg属性:index:指定参数在构造函数参数列表的索引位置type:指定参数在构造函数中的数据类型name:指定参数在构造函数中的名称 用这个找给谁赋值 =======上面三个都是找给谁赋值,下面两个指的是赋什么值的==============value:它能赋的值是基本数据类型和 String 类型ref:它能赋的值是其他 bean 类型,也就是说,必须得是在配置文件中配置过的 bean -->优势 在获取bean对象时,注入数据是必须的操作,否则对象无法创建成功
弊端 改变了bean对象的实例化方式,使我们在创建对象时,如果用不到这些数据,也必须提供
具体代码如下:
/***/public class AccountServiceImpl implements IAccountService {private String name;private Integer age;private Date birthday;public AccountServiceImpl(String name, Integer age, Date birthday) {this.name = name;this.age = age;this.birthday = birthday;}@Overridepublic void saveAccount() {System.out.println(name+","+age+","+birthday);}}
顾名思义,就是在类中提供需要注入成员的 set 方法
<!-- 通过配置文件给 bean 中的属性传值:使用 set 方法的方式
涉及的标签:property 属性:name:找的是类中 set 方法后面的部分ref:给属性赋值是其他 bean 类型的value:给属性赋值是基本数据类型和 string 类型的 实际开发中,此种方式用的较多。 -->优势 创建对象时没有明确的限制,可以直接使用默认构造函数
弊端 如果有某个成员必须有值,则获取对象时有可能set方法没有执行
具体代码如下:
/** */public class AccountServiceImpl implements IAccountService {private String name;private Integer age;private Date birthday;public void setName(String name) {this.name = name;}public void setAge(Integer age) {this.age = age;}public void setBirthday(Date birthday) {this.birthday = birthday;}@Overridepublic void saveAccount() {System.out.println(name+","+age+","+birthday);}}
/*** 使用 p 名称空间注入,本质还是调用类中的 set 方法*/public class AccountServiceImpl4 implements IAccountService {private String name;private Integer age;private Date birthday;public void setName(String name) {this.name = name;}public void setAge(Integer age) {this.age = age;}public void setBirthday(Date birthday) {this.birthday = birthday;}@Overridepublic void saveAccount() {System.out.println(name+","+age+","+birthday);}}
配置文件代码:
<!-- 注入集合数据 List 结构的: array,list,set Map 结构的 map,entry,props,prop -->
/***/public class AccountServiceImpl implements IAccountService {private String[] myStrs;private ListmyList;private Set mySet;private Map myMap;private Properties myProps;public void setMyStrs(String[] myStrs) {this.myStrs = myStrs;}public void setMyList(List myList) {this.myList = myList;}public void setMySet(Set mySet) {this.mySet = mySet;}public void setMyMap(Map myMap) {this.myMap = myMap;}public void setMyProps(Properties myProps) {this.myProps = myProps;}@Overridepublic void saveAccount() {System.out.println(Arrays.toString(myStrs));System.out.println(myList);System.out.println(mySet);System.out.println(myMap);System.out.println(myProps);}} AAA BBB CCC AAA BBB CCC
AAA BBB CCC aaa bbb
转载地址:https://blog.csdn.net/m0_56426304/article/details/118003966 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!