Spring(二)

Spring

(一)、IOC创建对象的方式

第一种使用无参构造创造对象————默认

第二种 我们要使用有参构造创建对象

  1. 下标赋值

    <!--第一种,下标赋值!-->
    <bean id="user" class="com.kuang.pojo.User">
        <constructor-arg index="0" value="狂神说Java"/>
    </bean>
    
  2. 类型

    <!--第二种方式:通过类型创建,不建议使用!-->
    <bean id="user" class="com.kuang.pojo.User">
        <constructor-arg type="java.lang.String" value="秦正"/>
    </bean>
    

    3.参数名

    <!--第三种,直接通过参数名来设置-->
    <bean id="user" class="com.kuang.pojo.User">
        <constructor-arg name="name" value="秦正"/>
    </bean>
    

    总结:在配置文件加载的时候,容器中管理的对象就已经初始化了!

(二)、Spring配置

1、别名
<!--别名,如果添加了别名,我们也可以使用别名获取到这个对象-->
<alias name="user" alias="userNew"/>

2、Bean的配置

<!--
    id : bean 的唯一标识符,也就是相当于我们学的对象名
    class : bean 对象所对应的全限定名 : 包名 + 类型
    name :也是别名,而且name 可以同时取多个别名
    -->
<bean id="userT" class="com.kuang.pojo.UserT" name="user2 u2,u3;u4">
    <property name="name" value="西部开源"/>
</bean>

3.import

这个import,一般用于团队开发使用,他可以将多个配置文件,导入合并为一个

假设,现在项目中有多个人开发,这三个人复制不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的!

  • 张三

  • 李四

  • 王五

  • applicationContext.xml

    <import resource="beans.xml"/>
    <import resource="beans2.xml"/>
    <import resource="beans3.xml"/>
    

使用的时候,直接使用总的配置就可以了

(三)、依赖注入

1、构造器注入
<!--第一种,下标赋值!-->
<bean id="user" class="com.kuang.pojo.User">
    <constructor-arg index="0" value="狂神说Java"/>
</bean>
<!--第二种方式:通过类型创建,不建议使用!-->
<bean id="user" class="com.kuang.pojo.User">
    <constructor-arg type="java.lang.String" value="秦正"/>
</bean>
<!--第三种,直接通过参数名来设置-->
<bean id="user" class="com.kuang.pojo.User">
    <constructor-arg name="name" value="秦正"/>
</bean>

2、Set方式注入

依赖注入:Set注入!要求被注入的属性,必须有set方法,而且set方法的名字需要规范(set+属性名,且属性名的首字母要大写)

  • 依赖:bean对象的创建依赖于容器!
  • 注入: bean对象中的所有属性,由容器来注入!

1、复杂类型

public class Address {
    private String address;

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

}

2、真实测试对象

public class Student {

private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;

}

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

<bean id="address" class="com.kuang.pojo.Address">
    <property name="address" value="西安"/>
</bean>

<bean id="student" class="com.kuang.pojo.Student">
    <!--第一种,普通值注入,value-->
    <property name="name" value="秦正"/>

​    <!--第二种,Bean注入,ref-->
​    <property name="address" ref="address"/>

​    <!--数组-->
​    <property name="books">
​        <array>
​            <value>红楼梦</value>
​            <value>西游记</value>
​            <value>水浒传</value>
​            <value>三国演义</value>
​        </array>
​    </property>

​    <!--List-->
​    <property name="hobbys">
​        <list>
​            <value>听歌</value>
​            <value>敲代码</value>
​            <value>看电影</value>
​        </list>
​    </property>

​    <!--Map-->
​    <property name="card">

        <map>
            <entry key="身份证" value="111111222222223333"/>
            <entry key="银行卡" value="1321231312312313123"/>
        </map>

​    </property>

​    <!--Set-->
​    <property name="games">
​        <set>
​            <value>LOL</value>
​            <value>COC</value>
​            <value>BOB</value>
​        </set>
​    </property>

​    <!--null-->
​    <property name="wife">
​        <null/>
​    </property>

​    <!--Properties-->
​    <property name="info">
​        <props>
​            <prop key="driver">20190525</prop>
​            <prop key="url">男</prop>
​            <prop key="username">root</prop>
​            <prop key="password">123456</prop>
​        </props>
​    </property>
</bean>

</beans>

测试

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.getAddress());
    }
}

3、拓展方式注入

我们可以使用 p命令空间和c命令空间进行注入

注意点:p命名和c命名空间不能直接使用,需要导入xml约束!

xmlns:c=“http://www.springframework.org/schema/c”
xmlns:p=“http://www.springframework.org/schema/p”

在这里插入图片描述

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

<!--p命名空间注入,可以直接注入属性的值:property-->
<bean id="user" class="com.qin.pojo.User" p:name="秦正" p:age="18"/>

<!--c命名空间注入,通过构造器注入:construct-args-->
<bean id="user2" class="com.qin.pojo.User" c:age="18" c:name="秦正"/>

</beans>
@Test
public void test2(){
    ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
    User user = context.getBean("user2", User.class);
    System.out.println(user);
}

4、bean的作用域 scope

在这里插入图片描述
在这里插入图片描述

单例模式 (Spring默认机制)

<bean id="user2" class="com.kuang.pojo.User" c:age="18" c:name="秦正" scope="singleton"/>

原型模式:每次从容器中get的时候,都会产生一个新对象!

<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>

其余的 request、session、application、这些个只能在web开发中使用到

(四)Bean的自动装配

  • 自动装配是Spring满足bean依赖一种方式!
  • Spring会在上下文中自动寻找,并自动给bean装配属性!

在Spring中有三种装配的方式

  1. 在xml中显示的配置
  2. 在java中显示配置
  3. 隐式 的自动装配bean 【重要】

1、测试

环境搭建:一个人有两个宠物!

2、ByName自动装配

<!--
    byName: 会自动在容器上下文中查找,和自己对象set方法后面的值对应的 beanid!
    -->
<bean id="people" class="com.kuang.pojo.People" autowire="byName">
    <property name="name" value="小狂神呀"/>
</bean>

3、ByType自动装配

<bean class="com.qin.pojo.Cat"/>
<bean class="com.qin.pojo.Dog"/>

<!--
    byName: 会自动在容器上下文中查找,和自己对象set方法后面的值对应的 beanid!
    byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean!
    -->
<bean id="people" class="com.kuang.pojo.People" autowire="byType">
    <property name="name" value="小狂神呀"/>
</bean>

小结:

  • byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
  • bytype的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!

4.使用注解实现自动装配

jdk1.5支持的注解,Spring2.5就支持注解了!

The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.

要使用注解须知:

  1. 导入约束 : context约束
  2. ==配置注解的支持 :context:annotation-config/ 【重要!】

在这里插入图片描述

@Autowired(开发中常用)

直接在属性上使用即可!也可以在set方式上使用!

使用Autowired 我们可以不用编写Set方法了,前提是你这个自动装配的属性在 IOC(Spring)容器中存在,且符合名字byname!

科普:

@Nullable   字段标记了这个注解,说明这个字段可以为null;
public @interface Autowired {
    boolean required() default true;
}

测试代码

public class People {
    //如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;
}

如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候、我们可以使用@Qualifier(value=“xxx”)去配置@Autowired的使用,指定一个唯一的bean对象注入!

@Resource
@Qualifier(value = "dog123")
private Dog dog;

@Resource注解

public class People {

@Resource(name = "cat2")
private Cat cat;

@Resource
private Dog dog;

}

@Resource 和@ Autowired 的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @ Autowired 通过byType的方式实现,而且必须要求这个对象存在! 【常用】
  • @ Resource 默认通过byname的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错! 【常用】
  • 执行顺序不同:@ Autowired 通过byType的方式实现。@ Resource 默认通过byname的方式实现。

(四)、使用注解开发

在Spring4之后,要使用注解开发,必须要保证 aop的包导入了

在这里插入图片描述

<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.kuang"/>
<context:annotation-config/>

使用注解需要导入context约束,增加注解的支持!

1.属性如何注入

@Component
public class User {

public String name;

//相当于 <property name="name" value="kuangshen"/>
@Value("kuangshen2")
public void setName(String name) {
    this.name = name;
}

}

2、衍生的注解

@Component 有几个衍生注解,我们在web开发中,会按照mvc三层架构分层!

  • dao 【@Repository】

  • service 【@Service】

  • controller 【@Controller】

    这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean

3、自动装配置
  •   - @Autowired :自动装配通过类型。名字
        如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value="xxx")
      - @Nullable   字段标记了这个注解,说明这个字段可以为null;
      - @Resource  :自动装配通过名字。类型。
    

4、作用域

@Scope("prototype")

小结:xml 与 注解:

  • xml 更加万能,适用于任何场合!维护简单方便
  • 注解 不是自己类使用不了,维护相对复杂!

xml 与 注解最佳实践:

  • xml 用来管理bean;
  • 注解只负责完成属性的注入;
  • 我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支

5、使用Java的方式配置Spring

我们现在要完全不使用Spring的xml配置了,全权交给Java来做!

JavaConfig 是Spring的一个子项目,在Spring 4 之后,它成为了一个核心功能!

//这里这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中

@Component
public class User {
    private String name;

public String getName() {
    return name;
}

@Value("QINJIANG") //属性注入值
public void setName(String name) {
    this.name = name;
}

@Override
public String toString() {
    return "User{" +
            "name='" + name + '\'' +
            '}';
}

}

配置文件

// 这个也会Spring容器托管,注册到容器中,因为他本来就是一个@Component
// @Configuration代表这是一个配置类,就和我们之前看的beans.xml
@Configuration
@ComponentScan("com.qin.pojo")
@Import(KuangConfig2.class)
public class KuangConfig {

//注册一个bean , 就相当于我们之前写的一个bean标签
//这个方法的名字,就相当于bean标签中的id属性
//这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User user(){
    return new User(); //就是返回要注入到bean的对象!
}

}

测试类!

public class MyTest {
    public static void main(String[] args) {
        //如果完全使用了配置类方式去做,我们就只能通过 AnnotationConfig 上下文来获取容器,通过配置类的class对象加载!
        ApplicationContext context = new AnnotationConfigApplicationContext(KuangConfig.class);
        User getUser = (User) context.getBean("user");
        System.out.println(getUser.getName());
    }
}

个bean , 就相当于我们之前写的一个bean标签
//这个方法的名字,就相当于bean标签中的id属性
//这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User user(){
return new User(); //就是返回要注入到bean的对象!
}

}


测试类!

public class MyTest {
public static void main(String[] args) {
//如果完全使用了配置类方式去做,我们就只能通过 AnnotationConfig 上下文来获取容器,通过配置类的class对象加载!
ApplicationContext context = new AnnotationConfigApplicationContext(KuangConfig.class);
User getUser = (User) context.getBean(“user”);
System.out.println(getUser.getName());
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值