项目结构:

Spring知识点练习

<?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">
   <!-- 在beans中添加default-lazy-init="true"可声明全局Bean均为懒加载 -->
      
    <!-- 依赖注入 -->
    <!-- 声明一个Bean -->
    <!-- lazy-init="true"声明为懒加载 -->
    <!-- <bean name="studentService" class="org.Spring_Ioc.service.impl.StudentServiceImpl" lazy-init="true" /> -->
    
    <!-- 注入工厂 -->
    <!-- <bean name="studentFactory" class="org.Spring_Ioc.factory.StudentFactory" /> -->
      
      <!-- Spring内置工厂注入 -->
    <!-- <bean name="studentService" factory-bean="studentFactory" factory-method="studentService" /> -->
    <!-- spring内置工厂默认为单例模式,添加scope="protopye"属性后表明为多例模式 -->
    <bean name="studentService" class="org.Spring_Ioc.factory.StudentFactory" factory-method="studentService" scope="protopye" />
    
    
    <!-- Bean的生命周期-在创建Bean的前后(容器销毁的时候执行)指定执行某些方法 -->
    <!-- 为Bean添加autowire="byName"属性
        当配置文件中被调用者 Bean的   id值与代码中调用者  Bean类的属性名相同时,
        可使用byName方式,让容器自动将被调用者  Bean注入给调用者  Bean,即在此处不再配置类对象成员变量 -->
    <!-- <bean id="mySchool" /> -->
    <bean name="studentService" class="org.Spring_Ioc.service.impl.StudentServiceImpl" init-method="Before" destroy-method="After">
        <!-- 此处配置的参数是Bean中的成员变量,需要有Getter和Setter方式 -->
        <property name="name" value="John"></property>
        <!-- 成员变量是一个对象 ,单独定义一个mySchool的Bean,可在Bean中初始化其成员变量-->
        <property name="school" ref="mySchool"></property>
        <!-- 使用SPEL注入,调用库方法 -->
        <property name="age2" value="#{T(java.lang.Math).random()*30.0}"></property>
        <!-- 调用另一个Bean中定义的值 -->
        <property name="age2" value="#{person.personAge}"></property>
        
    </bean>
    
</beans>

public class StudentFactory {

    public static StudentService studentService() {
        return new StudentServiceImpl();
    }
    
}
 

public class IoCApplication {
    public static void main( String[] args ) {
        //创建容器
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //从容器中获取对象
//        StudentService service = (StudentService)context.getBean("studentService");
//        service.doSome();
        
        //注入工厂,缺陷在于不能直接单例或者多例切换,耦合性增强
//        StudentFactory st = (StudentFactory)context.getBean("studentFactory");
//        st.studentService().doSome();
        
        //Spring工厂实现的是单例模式
        StudentService st1 = (StudentService)context.getBean("studentService"); 
        System.out.println(st1); //[email protected]
        StudentService st2 = (StudentService)context.getBean("studentService");
        System.out.println(st2); //[email protected]
        
    }
}

相关文章: