Spring开始

本文详细介绍了Spring框架的作用及其核心概念——依赖注入(IOC)与面向切面编程(AOP)。通过实例展示了如何使用XML配置文件进行bean的装配及利用静态工厂和动态工厂创建bean。此外,还介绍了bean的生命周期管理。

Spring

     主要作用:spring的主要作用是解耦,降低代码间的耦合度(指降低类和类之间的耦合度)。根据功能的不同,可以将系统中的代码分成主业务逻辑和系统级业务逻辑两类。Spring根据代码功能的特点,降低耦合度的方式分为两类:Ioc(控制反转)和AOP(面向切面编程)至于这两种方式的具体解释后面再说,或者自己查。Spring是一个容器,

1.1Spring与IOC

  1.1.1bean的装配(上代码)
<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        <!--注册service对象,通过动态工厂生成service对象,然后直接通过配置文件将改对象放入Spring的Bean容器中,这里的init-method, destroy-method是两个方法在某个类中-->
    <bean id="someService1" class="com.ba04.SomeServiceImp" init-method="initAfter" destroy-method="descory"></bean>
    <!--bean后处理器-->
    <bean class="com.ba04.MyBeanPost"></bean>
      
</beans>

    @Test     //Junit调试
    public void mytest02() {
        //加载spring配置文件,创建spring容器对象,在执行配置文件时,配置文件中添加的对象都会被创建出来,
        ApplicationContext ac= new ClassPathXmlApplicationContext("com/ba04/applicationContext.xml");
        //获取需要的对象
        ISomeService service1 =(ISomeService) ac.getBean("someService1");
        String name=service1.doFirst();
        service1.dosercend();
        System.out.println(name);
        System.out.println("-----------------------------");
        ((ClassPathXmlApplicationContext)ac).close();
    }

1.1.2 bean工厂(静态工厂和动态工厂)这里只放了两个关键代码,静态工厂加个static关键字,然后因为是静态可以直接获取所以在注释里

//动态工厂,
public class ServiceFactory {
        public ISomeService getSomeService() {
            return new SomeServiceImp();
        }
}

<?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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--注册service对象,通过动态工厂生成service对象,然后直接通过配置文件将改对象放入Spring的Bean容器中-->
        <!--scope="prototype" 原型模式:真正使用时才创建,每获取一次都会创建不同的对象 -->
    <!--(默认)scope="singleton" 单例模式:容器初始化时就创建,每次获取的都是同一个对象 -->
    <bean id="serviceFactory" class="com.ba01.ServiceFactory" />
    <!-- bean 中油专门的方法可以通过他直接用动态工厂中的方法来获取需要的对象 -->
        <!--<bean id="someService" class="com.ba02.ServiceFactory" factory-method="getSomeService"></bean>-->
    <bean id="someService" factory-bean="serviceFactory" factory-method="getSomeService"></bean>

</beans>

转载于:https://www.cnblogs.com/saber114567/p/10391094.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值