spring学习

1.ApplicationContext 代表 Spring IOC容器。

  IOC:(Inversion of Control)反转资源获取的方向,即由容器为其管理的类分配资源。

  DI:(Dependence Injection)依赖注入,将容器配置好的参数注入到其管理的类中。

2.ClassPathXmlApplicationContext 是 ApplicationContext 接口 的 实现类,并从类路径下加载配置文件。

3.获取bean,bean接口在 ClassPathXmlApplicationContext  的副接口 BeanFactory中进行初始化。

  //2.从IOC容器中获取bean实例(利用id定位bean)

  HelloWorld hw = (HelloWorld)ctx.getBean("helloWorld");

  //2.用类型获取(要求IOC容器中只有一个该类型的bean)

  HelloWorld hw = ctx.getBean(HelloWorld.class);

4.DI(依赖注入):(还有一种工厂方法注入(不推荐使用))

    属性注入:(最常用)通过get、set方法注入,对应配置标签<property>

<bean id="helloWorld" class="com.springstudy1.beans.HelloWorld">
	<property name="name" value="spring"></property>
</bean>

    构造器注入:通过构造方法注入,对应配置标签<congstructor-arg>

<bean id="car" class="com.springstudy1.beans.Car">
	<constructor-arg index="0" value="Audi" type="String"></constructor-arg>
	<constructor-arg index="1" value="ShangHai" type="String"></constructor-arg>
	<constructor-arg index="2" value="300000" type="double"></constructor-arg>
</bean>
<!-- 通过index位置或type类型区分重载构造器 <bean id="car2" class="com.springstudy1.beans.Car"> <constructor-arg index="0" value="Benchi" type="String"></constructor-arg> <constructor-arg index="1" value="German" type="String"></constructor-arg> <constructor-arg index="2" value="240" type="int"></constructor-arg> </bean>
public Car(String brand, String crop, double price) {
    super();
    this.brand = brand;
    this.crop = crop;
    this.price = price;
}

public Car(String brand, String crop, int maxspeed) {
    super();
    this.brand = brand;
    this.crop = crop;
    this.maxspeed = maxspeed;
}
    

 5.MySQL连接jar包下载地址 https://mvnrepository.com/artifact/mysql/mysql-connector-java 

6.基于注解的方式进行配置:

7.@Autowired(@Autowired(required=false))

默认情况下, 所有使用 @Autowired 注解的属性都需要被设置.当 Spring 找不到匹配的 Bean 装配属性时, 会抛出异常,

若某一属性允许不被设置, 可以设置 @Autowired 注解的 required 属性为 false

8.@Qualifier(@Qualifier("userJdbcRepository"))

默认情况下, 当 IOC 容器里存在多个类型兼容的 Bean 时, 通过类型的自动装配将无法工作.

此时可以在 @Qualifier 注解里提供 Bean 的名称. Spring 允许对方法的入参标注 @Qualifiter 已指定注入 Bean 的名称。

总结:

各个资源类通过配置文件将需要的资源告知容器,容器在资源初始化的时候将各个资源类所需的资源分配给他们。

(减少了资源初始化的次数以及占用的硬件资源,只需要在容器中初始化一次即可)

原文地址:https://www.cnblogs.com/yuntianblog/p/13390849.html