学习SpringFramework-IOC(控制反转)容器初始化

1.ApplicationContext实现类

ClassPathXmlApplicationContext:用于加载类路径下的spring配置文件

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        App app = ctx.getBean(App.class);
        app.testFruit();

AnnotationConfigApplicationContext:用于初始化通过注解方式配置的ioc容器

ApplicationContext ctx = new AnnotationConfigApplicationContext(App.class);
        Apple app = ctx.getBean(Apple.class);
        app.eatFruit();

FileSystemXmlApplicationContext:用于加载本地目录中的spring文件文件

 ApplicationContext ctx = new FileSystemXmlApplicationContext("D:/applicationContext.xml");
        App app = ctx.getBean(App.class);
        app.testFruit();

XmlWebApplicationContext:用于在Web工程中初始化SpringIOC容器,不过我们一般不会手动通过它来初始化IOC容器,Spring针对Web工程专门给我们提供了一个监听器来完成IOC容器的初始化工作,用法如下:
在项目的web.xml中配置

<!-- 通过Spring提供的ContextLoaderListener监听器完成Spring容器初始化 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

在ContextLoaderListener中Spring会优先判断用户是否在web.xml中配置了名为contextClass的参数,如果配置了优先使用用户制定的ApplicationContext实现类来初始化IOC,反之则使用默认的ApplicationContext实现类:org.springframework.web.context.support.XmlWebApplicationContext来完成IOC容器的初始化工作。

注:XmlWebApplicationContext默认加载路径是/WEB-INF/applicationContext.xml,如果我们的配置spring文件是放在这里的,并且只有这一个,我们可以不配置contextConfigLocation参数。

Application初始化路径

路径前缀classpath:项目的classpath下相对路径

ApplicationContext  ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

路径通配符classpath*:加载所有符合条件的文件

ApplicationContext  ctx = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");

通过xml方式配置管理bean

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config/>
    <context:component-scan base-package="com.lanou3g.spring" />

    <bean id=" " class=" " />
    <bean id=" "class=" ">
        <property name="  " ref="  " />
    </bean>
</beans>

优点:
1、xml 作为可扩展标记语言最大的优势在于开发者能够为软件量身定制适用的标记,使代码更加通俗易懂。
2、修改配置而无需变动现有程序。
3、具有成熟的验证机制确保程序正确性。
缺点:
1、解析 xml 势必会影响应用程序性能,占用系统资源。
2、配置文件过多导致管理变得困难。
3、查错变得困难。往往配置的一个手误导致莫名其妙的错误。
【注意】schema约束地址不能用https,否则每次运行都要从spring网上加载,无网不能运行,把https改为http就会先从本地寻找所需依赖,找不到才会从网上加载

通过注解方式管理bean

@Configuration
@ComponentScan(basePackages = "com.lanou3g.spring")
public class App {

    @Autowired
    @Qualifier("ap") //这里写的apple对应的是bean的id或者name
    private Fruit fruit;

    public void testFruit() {
        fruit.eatFruit();
    }

}

Spring支持通过注解的方式来配置bean
@Configuration` 注解的类相当于xml配置文件中的
@ComponentScan主要就是定义扫描的路径从中找出标识了需要装配的类自动装配到spring的bean容器中
@Component、@Repository、 @Service、@Controller
@Component注解是一个通用注解,代表一个组件,可以用来标识所有希望让Spring管理的bean。
@Repository、 @Service、@Controller三个注解扩展自@Component,带有具体的语义色彩,专门用于修饰dao、service、controller层的类

@Scope`注解可以限定通过注解配置的bean的作用域。
@Qualifier该注解可以让我们通过名称在多个候选bean中进一步限定
@Import通过注解的方式导入其他注解配置
优点:
1、XML配置起来有时候冗长,此时注解可能是更好的选择
2、注解相对于XML的另一个好处是类型安全的,XML只能在运行期才能发现问题
3、使用起来直观且容易,提升开发效率
缺点:
1、使用spring注解时,会发现注解分散到很多类中,不好管理和维护
2、XML方式比注解的可扩展性和复杂性维护上好的多
3、通用的配置还是XML比较好,只需要学一遍就行

xml和注解一起使用

@Configuration
@ImportResource("applicationContext.xml")
public class App {

    @Autowired
    @Qualifier("ap") //这里写的apple对应的是bean的id或者name
    private Fruit fruit;

    public void testFruit() {
        fruit.eatFruit();
    }

}

@ImportResource是引入spring配置文件.xml,管理配置的bean

在XML文件中写入:

 <context:annotation-config />

    <context:component-scan base-package="com.lanou3g.spring" />

引入context命名空间,在配置文件中添加context:annotation-config标签

在一个配置中导入里一个配置

xml导入

导入其他spring配置文件 
      <import resource="classpath:message_beans.xml" />

这样可以解决当我们的bean很多时,不方便管理,可以使用多个XML文件,把多个文件导入到一个主文件中.

注解导入

@Import(MyConf.class)
@ImportResource("applicationContext.xml")

@Import注解是引入带有@Configuration的java类,类似于spring配置文件里的import标签,将多个配置文件导入到一个主配置文件里
@ImportResource是引入spring配置文件.xml,管理配置的bean

IOC中bean的作用域

ScopeDescription
singleton单例。在整个ioc容器中只有一个此类型的示例。(默认值)
prototype原型。每次使用都用创建一个新的对象。
request对象的实例仅在一个request请求周期内有效,仅限在web环境中使用。
session对象的实例仅在一个session会话周期内有效,仅限在web环境中使用。
application对象的实例在整个application生命周期内有效,仅限在web环境中使用。
websocket对象的实例仅在一个websocket生命周期内有效,仅限在web环境中使用。

singleton(单例)
在每个Spring IoC容器中,一个bean定义只有一个对象实例。

     <bean id="banana" scope="singleton" class="com.lanou3g.spring.simple.Banana" />

 //不写也可以,默认就是单例

使用接口

 public static void main(String[] args) {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        Banana b=ctx.getBean("banana",Banana.class);
        System.out.println(b);
        Banana b1=ctx.getBean("banana",Banana.class);
        System.out.println(b1);
        Banana b2=ctx.getBean("banana",Banana.class);
        System.out.println(b2);
        }

三次打印地址,控制台输出的都是同一个地址,所以singleton是单实例,每次getBean都是获取同一个对象
prototype(非单例)
每次调用getBean,都会一个新的bean

       <bean id="banana" scope="prototype" class="com.lanou3g.spring.simple.Banana" />

再次打印,在控制台就会输出三个不同的地址

com.lanou3g.spring.simple.Banana@6c40365c
com.lanou3g.spring.simple.Banana@7bedc48a
com.lanou3g.spring.simple.Banana@131ef10

Bean的生命周期

通过xml中给bean配置init-method、destroy-method属性

    <bean id="banana" class="com.lanou3g.spring.simple.Banana" init-method="myInit" destroy-method="myDestroy" />

Java创建myInit和myDestroy方法:

public class Banana implements Fruit {
    public void myInit() {
        System.out.println("init");
    }

    public void myDestroy() {
        System.out.println("destroy");
    }
    @Override
    public void eatFruit() {
        System.out.println("eating Banana");
    }
}

使用入口

public static void main(String[] args) {

        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        ctx.registerShutdownHook();
        }

控制台输出

init
destroy

设置默认生命周期方法
如果你的工程中有几十个类都需要添加自定义生命周期方法,以便完成一些初始化和销毁的操作。你可以设置所有的初始化生命周期方法都叫init,所有的销毁生命周期方法都叫destroy。 这种情况下我们无需每个bean都配置一遍生命周期方法,spring给我们提供了一下方式可以完成:

<!-- 在beans上添加default-init-method、default-destroy-method属性,所有在beans范围内配置的bean如果没有显示指定init-method、destroy-method,会默认使用beans上的配置 -->
<beans default-init-method="init" default-destroy-method="destroy">
</beans>

id和name命名bean

使用id属性命名bean
id属性的值只能指定一个,不建议含有特殊字符(虽然自spring3.1开始id属性的值可以包含任意字符)。

使用name属性命名bean
使用name属性可以给一个bean指定多个名称,多个值之间可以用逗号(“,”)隔开
【注意】我们可以同时指定id和name属性。 也可以都不指定,如果都不指定,IOC容器会为该bean生成一个唯一的名称(类名首字母小写)。

实例化bean

通过构造方法实例化
这种方式是最常用的方式,适合绝大多数的javabean,因为我们的java类无需继承任何父类或实现任何接口。但是我们通常需要提供一个无参的构造方法。

<bean id="exampleBean" class="examples.ExampleBean"/>

<bean name="anotherExample" class="examples.ExampleBeanTwo"/>

通过静态工厂方法实例化

<bean id="clientService" class="examples.ClientService" factory-method="createInstance">
	<!-- 如果工厂方法需要参数,通过此标签传参 -->
  <constructor-arg name="cname" value="TestService" />
</bean>
public class ClientService {
    private static ClientService clientService = null;
  	private String cname;
    private ClientService() {}
  	private ClientService(String cname) {this.cname = cname;}

    public synchronized static ClientService createInstance(String cname) {
        if(clientService == null) {
           clientService = new ClientService(cname);
        }
      return clientService;
    }
  
  	public synchronized static ClientService createInstance() {
        if(clientService == null) {
           clientService = new ClientService();
        }
      return clientService;
    }
}

这种方式适合需要让Spring管理自己实现的单例类,用的很少。因为通过Spring IOC容器我们只需配置一下scope="singleton"就可以实现单例了。
通过对象工厂方法实例化

<!-- the factory bean, which contains a method called createClientServiceInstance() -->
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
    <!-- inject any dependencies required by this locator bean -->
</bean>

<!-- the bean to be created via the factory bean -->
<bean id="clientService"
    factory-bean="serviceLocator"
    factory-method="createClientServiceInstance"/>

<!-- the bean to be created via the factory bean -->
<bean id="accountService"
    factory-bean="serviceLocator"
      factory-method="createAccountServiceInstance">

  	<!-- 如果工厂方法需要参数,通过此标签传参 -->
  	<!-- <constructor-arg name="cname" value="TestService" /> -->
  
</bean>
public class DefaultServiceLocator {

    private static ClientService clientService = new ClientServiceImpl();

  	private static AccountService accountService = new AccountServiceImpl();
  
    public ClientService createClientServiceInstance() {
        return clientService;
    }
  
  	public AccountService createAccountServiceInstance() {
        return accountService;
    }
}

关闭SpringIOC容器

我们可以通过registerShutdownHook()实现在JVM停止的同时优雅的关闭IOC容器

public static void main(String[] args) {

        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        ctx.registerShutdownHook();
        }

懒加载

什么是懒加载
当我们在spring容器启动的时候先不把所有的bean都加载到spring容器中,而是在需要用的时候,才把这个对象实例化到容器中。
实现方式
给bean添加一个init-lazy="true"延迟初始化的时机到getBean的时候。

<bean lazy-init="true"/>
//用lazy-init。告诉spring容器是否以懒加载的方式创造对象。用的时候才加载构造,不用的时候不加载
取值:true(懒,真正调用到的时候再加载)、false(非懒,已启动spring容器就创建对象)、default(懒)

懒加载的优缺点
对象使用的时候才去创建,节省资源,但是不利于提前发现错误。
全局懒加载
如果很多的bean都不想在IOC容器启动的时候就加载, 我们只要在beans的头里面加上default-lazy-init就ok 了

<beans  default-lazy-init ="true">
</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值