Spring学习笔记(二)之Spring 的配置、实例化bean、依赖注入

       第二次学习笔记总结了6点内容,分别是:Spring 的三种配置方法、实例化bean的三种方式、依赖注入的两种方式、自动装配、延迟初始化、Spring的作用域scope

1. Spring 的三种配置方法

1.1  用 XML 配置,

 参考 学习笔记(一)中的程序

1.2  用 Annotation 自动扫描装配

step1:导入jar包

  • commons-logging-1.2.jar
  • spring-core-4.3.7.RELEASE.jar
  • spring-beans-4.3.7.RELEASE.jar
  •  spring-context-4.3.7.RELEASE.jar
  •  spring-test-4.3.7.RELEASE.jar

这里使用maven项目,在pom.xml文档中导入jar包

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.xzy.spring</groupId>
  <artifactId>sp02_Maven</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>sp03_Annocation</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
  
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.1.8.RELEASE</version>
    
     <exclusions>
            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
            </exclusion>
     </exclusions>
</dependency>
  
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.8.RELEASE</version>
</dependency>

  <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>5.1.8.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.1.8.RELEASE</version>
</dependency>

   <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.25</version>
    <scope>test</scope>
</dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  
  <build>
    <finalName>sp03_Annocation</finalName>
    <plugins>
		<plugin>
			<artifactId>maven-compiler-plugin</artifactId>
			  <configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>utf-8</encoding>
			  </configuration	>
		</plugin>
    </plugins>
  </build>
</project>

step2:编写javabean代码 

@Component
public class Teacher {
	 String name;
	   int age;
	   
	public Teacher() {
		this.name="zhangsan";
		this.age=99;
	}
@Component
public class Student 
{
   String name;
   int age;
   
   @Autowired
   Teacher tea;
   
public Student() {
	this.name="张三";
	this.age=55;
}

 step3:xml 配置文件ApplicationContext.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-4.3.xsd">
  
    <context:annotation-config/>
   <context:component-scan base-package="com.pojo"></context:component-scan>
</beans>

 

 step4:编写测试代码

package com.xzy.spring.sp02_Maven;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.pojo.Student;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value={"/ApplicationContext.xml"})
public class AppTest {
	
	@Autowired
	Student stu;
	
   @Test
    public void AppTest( )
    {
	   System.out.println(stu.getName()+"\t"+stu.getAge()+"\t"+stu.getTea());
    }

}

输出结果: 张三    55    Teacher [name=zhangsan, age=99]

1.3    用 Java 显式配置

step1:增加一个clazz类,不做任何配置

public class Clazz {
    private String name;

step2:删掉第二种方式的xml 配置文件,重新编写一个配置类

 @Bean作用在于:将返回的clazz对象放进spring容器

@Configuration
@ComponentScan(basePackages= {"com.pojo"})
public class StudentConfig {
    
	@Bean
	public Clazz createClazz() {
		
		Clazz clazz=new Clazz();
		clazz.setName("自动化专业");
		return clazz;
	}
}

step3:测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= {StudentConfig.class})
public class AppTest {
	
	@Autowired
	Student stu;
	@Autowired
	Clazz clazz;
	
   @Test
    public void AppTest( )
    {
	   System.out.println(stu.getName()+"\t"+stu.getAge()+"\t"+stu.getTea());
	   System.out.println(clazz.getName());
    }

}

测试结果: 

张三    55    Teacher [name=zhangsan, age=99]
自动化专业

代码结构图:

2. 实例化bean的三种方式

2.1 使用类构造器实例化 

默认使用不带参数的构造方法实例化 Bean 

<!-- 1、使用类构造器实例化 --> 
    <bean id="teacher" class="com.pojo.Teacher">
       <property name="name" value="哈哈哈"></property>
       <property name="age" value="44"></property>
   </bean>

2.2.使用静态工厂方法实例化

step1:javacode 构建StudentFactory类

public class StudentFactory {
	
	//使用静态工厂实例化
   public static Teacher createTeacher1() {
	   Teacher t1=new Teacher("诸葛亮",77);
	   return t1;
   }
}

step2:修改ApplicationContext.xml

<!-- 2.使用静态工厂方法实例化 -->  
   <bean id="teacher1"  class="com.factory.StudentFactory" factory-method="createTeacher1"></bean>

2.3.使用实例工厂方法实例化

step1:javacode 构建StudentFactory类

public class StudentFactory {
	
	//使用示例工厂实例化
   public Teacher createTeacher2() {
	   Teacher t2=new Teacher("周瑜",44);
	   return t2;
   }
}

step2:修改ApplicationContext.xml

  这里相当于先实例化teacherfactory,再通过createTeacher2,获得tea对象

<!-- 3.使用实例工厂方法实例化 -->  
   <bean id="teacherfactory"  class="com.factory.StudentFactory" ></bean>
   <bean id="teacher2" factory-bean="teacherfactory" factory-method="createTeacher2"></bean>

3.依赖注入的两种方式

  •  依赖注入(Dependency Injection,DI)在运行期,由外部容器动态地将依赖对象注入到组件中。换句话说,就是在运行时能 Bean对象设置属性值。
  • 依赖注入有两种方法,构造方法注入和 setter 方法注入。

3.1 构造方法注入

  包含名字和下标两种方式

<!-- 1、构造方法注入 --> 
    <bean id="teacher1" class="com.pojo.Teacher">
       <constructor-arg name="name" value="老刘"></constructor-arg>
        <constructor-arg name="age" value="36"></constructor-arg>
    </bean>
    
  <bean id="teacher2" class="com.pojo.Teacher">
       <constructor-arg index="0" value="王五"></constructor-arg>
        <constructor-arg index="1" value="46"></constructor-arg>
  </bean> 

3.2   setter 方法注入

   这里要注意编写的javabean类要包含对应的get()、set()方法。

<!--  setter方法注入 -->  
    <bean id="stu" class="com.pojo.Student">
       <property name="name" value="lisi44"></property>
       <property name="age" value="99"></property>
       <property name="tea" ref="teacher2"></property>
   </bean>

4. 自动装配

  • autowire byName (按名称自动装配)

      由于在手动配置xml过程中,常常发生字母缺漏和大小写等错误,而无法对其进行检查,使得开发效率降低。采用自动装配将避免这些错误,并且使配置简单化。

  当一个bean节点带有 autowire byName的属性时。

    ①将查找其类中所有的set方法名,例如setTea,获得将set去掉并且首字母小写的字符串,即tea。

    ②去spring容器中寻找是否有此字符串名称id的对象。

    ③如果有,就取出注入;如果没有,就报空指针异常。

    <bean id="stu1" class="com.bean.Student" autowire="byType">
  •  autowire byType (按类型自动装配)

      使用autowire byType首先需要保证:同一类型的对象,在spring容器中唯一。如果不唯一,会报不唯一的异常。

    <bean id="stu1" class="com.bean.Student" autowire="byName">

5. 延迟初始化

        默认情况下,Spring 容器在初始化过程中会创建和配置所有单例的bean。这种提前实例化是可取的,因为配置环境错误会被立即发现而不需要过多的时间。如果不采取这种行为,可以将单例的bean标记为延迟初始化。一个延迟初始化的bean告诉Spring IoC容器去创建这个bean实例化对象当它第一次被调用时而不是在容器启动时立即创建

 <bean id="stu" class="com.pojo.Student" lazy-init="true">

6. Spring的作用域scope

       singleton:spring的bean的默认的作用域-单例singleton。即在同一个容器或上下文中,所有对单例bean的请求,只要id与该bean定义相匹配,都会返回同一个实例。

       prototype:prototype就属于多例模式,每次请求都会创建一个新的实例,相当于new操作。

方法1.直接在配置文件ApplicationContext.xml中配置

 <bean id="stu" class="com.bean.Student" lazy-init="true" scope="prototype">

方法2:在annotation配置

@Component
@Scope("prototype")
public class Student

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值