Spring 入门(控制反转IOC、依赖注入DI、Bean的作用范围、Bean的生命周期)

 

1.什么是框架

框架(Framework)是整个或部分系统的可重用设计,表现为一组抽象构件及构件实例间交互的方法;另一种定义认为,框架是可被应用开发者定制的应用骨架。前者是从应用方面而后者是从目的方面给出的定义。

2. Java中的框架

Struts HiberNate Spring SpringMvc SpringBoot

 3. Struts2

Struts2是一个基于MVC设计模式的Web应用框架,它本质上相当于一个servlet,在MVC设计模式中,Struts2作为控制器(Controller)来建立模型与视图的数据交互

4. HiberNate

  1. 开源的对象关系映射框架

  2. 对jdbc的封装的框架

  3. 与pojo(JavaBean)建立映射关系

5. Spring

应用于web层的框架

JavaBean的管理

6. Java企业级开发的演化

  1. Servlet + Java Bean

  2. Servlet + Java Bean + Jsp

  3. Struts2 + Spring + HiberNate(SSH)

  4. Spring Mvc + Spring + mybatis(ibatis) (SSM)

  5. Spring Boot(下一代框架 微服务框架)

7. Spring

1. Spring的简介

Spring是分层的JavaSE/EE full-stack(一站式) 轻量级开源框架

分层:

  1. SUN提供的JavaEE的三层结构:web层、业务层(service)、数据访问层(dao)(持久层,集成层)

  2. Struts2是web层基于MVC设计模式框架.

  3. Hibernate是持久的一个ORM的框架.

一站式:

  1. Spring对web层提供的解决方案 : Spring Mvc

  2. Spring对Service层提供的解决方案 : Spring

  3. Spring对Dao层提供的解决方案 : Jdbc Template

常用的解决方案:

1. web (Struts2 SpringMvc)

2.service(Spring)

3.dao(DBUtils HiberNate mybatis Jdbc Template)

创建Spring项目:

依赖关系:

2. Spring的核心

1. IOC(控制反转)

把对象的创建权交给Spring容器

2. AOP(面向切面编程)

是面向对象的功能延伸.不是替换面向对象,是用来解决OOP(面向对象编程)中一些问题.

3. Spring的版本

spring3.x

spring4.x(推荐使用)

4. Spring的优点

  1. 方便解耦 简化开发

    把所有对象的创建交给Spring管理

  2. 支持Aop编程

    解决在OOP中遇到的一些问题

  3. 声明式事务的支持

  4. 方便调试程序

    在spring中有专门的调试模块Spring-Test

  5. 方便继承各种优秀的框架

    Spring对各种主流的框架都提供了支持

  6. Spring对一些比较难用的API都进行了封装,方便了程序猿的使用(邮件 远程调用....)

5. 日志框架

log4j:开源的优秀的日志框架

..........

日志门面:运行这些日志系统的

slf4j

logging (apache的日志门面)

Log log4j = Log log4j = LogFactory.getLog(TestLog.class);

log4j.info("info");

log4j.debug("debug");

log4j.error("error");

 

6. Spring的入门

创建实体类:

package com.ma.spring.demo01;



public class User {

private String name;

private Integer age;



public String getName() {

return name;

}



public void setName(String name) {

this.name = name;

}



public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

@Override

public String toString() {

return "User{" +

"name='" + name + '\'' +

", age=" + age +

'}';

}

}

1. pom依赖

<dependencies>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-core</artifactId>

<version>4.3.12.RELEASE</version>

</dependency>



<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-beans</artifactId>

<version>4.3.12.RELEASE</version>

</dependency>



<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-expression</artifactId>

<version>4.3.12.RELEASE</version>

</dependency>



<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>4.3.12.RELEASE</version>

</dependency>





<dependency>

<groupId>commons-logging</groupId>

<artifactId>commons-logging</artifactId>

<version>1.1.3</version>

</dependency>

<dependency>



<groupId>log4j</groupId>

<artifactId>log4j</artifactId>

<version>1.2.12</version>

</dependency>



</dependencies>

2. 创建log4j的配置文件

 

log4j.properties


### direct log messages to stdout ###

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.Target=System.out

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.rootLogger=debug, stdout

3. 创建Spring的配置文件

在resources目录下创建applicationContext.xml

引入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

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop.xsd">

<!-- 把User交给Spring管理-->

<bean id = "user" class = "com.ma.spring.demo01.User"></bean>

</beans>

4. 使用ApplicationContext创建对象

@Test

public void test01(){

//1、创建Spring的工厂对象(BeanFactory ApplicationContext)

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

//2、使用applicationContext.xml内部配置的bean来创建对象

User user = (User) applicationContext.getBean("user");

System.out.println(user);

}

7.ApplicationContext BeanFactory的区别

1.applicationContext继承自BeanFactory

2.在老版本中Spring中使用BeanFactory,在新版本中使用ApplicationContext

3.BeanFactory会在调用getBean时实例化对象,applicationContext会在容器加载的时候实例化对象

 

8.bean中name和id的区别

1.name和id都是用来给Spring管理的对象命名的

2.id遵循的是xml规范(唯一)

3.name可以配置多个(name = “user1,use2,user3”)

4.name可以出现特殊字符,id不可以出现特殊字符

5.一般使用id属性

 

9.属性的注入(DI)

DI:依赖注入 : 在对象的创建过程中给属性赋值

1.按构造器注入

<!--使用构造器注入属性-->

<constructor-arg name="age" value="21"></constructor-arg>

<constructor-arg name="name" value="小王"></constructor-arg>

2.按setter方法注入

<!--setter方法注入 property的name属性值为:setter方法的名字的首字母小写-->

<bean id = "user" class = "com.ma.spring.demo01.User">

<property name="age" value="20"></property>

<property name="name" value="小明"></property>

</bean>

 

开发过程中推荐使用setter方法注入

 

10.IOC和DI的区别

IOC : 把对象的创建权交给容器

DI : 创建对象时注入对象的属性 

 

11.Spring如何管理对象的创建

 

1、使用无参的构造器

<!--默认使用无参的构造器-->

<bean id = "user" class = "com.ma.spring.demo01.User">

</bean>

2、静态工厂实例化

静态工厂类

package com.ma.spring.demo01;



public class UserFactory {

public static User newInstance(){

return new User();

}

}

xml


 

<!--静态工厂创建对象-->

<bean id = "user" class = "com.ma.spring.demo01.UserFactory" factory-method="newInstance"

</bean>

3、实例工厂创建对象

实例工厂类
 

package com.ma.spring.demo01;



public class UserFactory {

public User newInstance(){

return new User();

}

}

xml


!--实例工厂创建对象-->

<bean id = "userFactory" class="com.ma.spring.demo01.UserFactory"></bean>

<bean id="user" factory-bean="userFactory" factory-method="newInstance"></bean>

12.Bean的作用范围

全局创建一个对象

<bean id = "user" class = "com.ma.spring.demo01.User" scope="singleton">

</bean>

调用一次对象创建一个

scope="prototype"


13.Bean的初始化和销毁

package com.ma.spring.demo01;



public class User {

private Integer age;

private String name;

public User(){

System.out.println("构造方法......");

}

public void init(){

System.out.println("初始化方法......");

}

public void destory(){

System.out.println("销毁方法......");

}

public String getName() {

return name;

}



public void setName(String name) {

this.name = name;

}



public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

}

xml

<bean id = "user" class = "com.ma.spring.demo01.User" scope="singleton" init-method="init" destroy-method="destory">

</bean>

 

容器创建时,会创建配置的Bean的对象,并且执行init()方法

//1、创建Spring的工厂对象(BeanFactory ApplicationContext)

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

//2、使用applicationContext.xml内部配置的bean来创建对象

User user1 = (User) applicationContext.getBean("user");

User user2 = (User) applicationContext.getBean("user");

System.out.println(user1);

System.out.println(user2);

Spring容器销毁的时候执行销毁方法

applicationContext.close();

 

 

14.Bean的生命周期

  1. instantiate bean对象实例化(如果scope="singleton"时,在容器加载时创建实例)

  2. populate properties 封装属性(DI)

  3. 如果Bean实现BeanNameAware 执行 setBeanName

  4. 如果Bean实现BeanFactoryAware 或者 ApplicationContextAware 设置工厂 setBeanFactory 或者上下文对象 setApplicationContext

  5. 如果存在类实现 BeanPostProcessor(后处理Bean) ,执行postProcessBeforeInitialization(aop的底层)

  6. 如果Bean实现InitializingBean 执行 afterPropertiesSet

  7. 调用<bean init-method="init"> 指定初始化方法 init

  8. 如果存在类实现 BeanPostProcessor(处理Bean) ,执行postProcessAfterInitialization

  9. 执行业务处理

  10. 如果Bean实现 DisposableBean 执行 destroy

  11. 调用<bean destroy-method="customerDestroy"> 指定销毁方法 customerDestroy

 

15.DI的复杂注入

 

1.普通的字面量的注入

<bean id = "user" class = "com.ma.spring.demo01.User">

<property name="age" value="20"></property>

<property name="name" value="小明"></property>

</bean>

2.对象注入

<bean id="user" class="com.ma.spring.demo01.User">

<property name="age" value="22"></property>

<property name="name" value="李四"></property>

</bean>

<bean id="orders" class="com.ma.spring.demo01.Orders">

<property name="user" ref="user"></property >

</bean>

测试类

package com.ma.spring.demo01;



import org.junit.Test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;



import java.beans.IntrospectionException;

import java.beans.PropertyDescriptor;

import java.lang.reflect.Method;



public class UserTest {

@Test

public void test01() {

//1、创建Spring的工厂对象(BeanFactory ApplicationContext)

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

//2、使用applicationContext.xml内部配置的bean来创建对象

Orders orders = (Orders) applicationContext.getBean("orders");



System.out.println(orders);

//applicationContext.close();

}

@Test

public void test02() throws ClassNotFoundException, IntrospectionException, IllegalAccessException, InstantiationException {

Class clazz = Class.forName("com.ma.spring.demo01.User");

//PropertyDescriptor propertyDescriptor = new PropertyDescriptor("name",clazz);

//System.out.println(propertyDescriptor.getWriteMethod().getName());

Object obj = clazz.newInstance();

for(Method method : clazz.getMethods()){

if(method.getName().startsWith("set")){

System.out.println(method.getName());

}

}



}

}

3.Map的注入

 

<!--注入Map-->

<bean id="user" class="com.ma.spring.demo01.User">

<property name="age" value="30"></property>

<property name="name" value="杰克"></property>

<property name="map">

<map>

<entry key="k1" value="v1"/>

<entry key="k2" value="v2"/>

<entry key="k3" value="v3"/>

</map>

</property>

</bean>

 

4.List的注入


 

<!--注入List-->

<bean id="user" class="com.ma.spring.demo01.User">

<property name="age" value="30"></property>

<property name="name" value="杰克"></property>

<property name="map">

<map>

<entry key="k1" value="v1"/>

<entry key="k2" value="v2"/>

<entry key="k3" value="v3"/>

</map>

</property>

<property name="hobbies">



<list>

<value>Java</value>

<value>Python</value>

<value>PHP</value>

</list>

</property>

</bean>

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值