关于spring一些简单介绍

1.p标签

xmlns:p="http://www.springframework.org/schema/p"

p标签是根据set注入

2.c标签

xmlns:c="http://www.springframework.org/schema/c"

c标签是根据构造方法注入

3.spring默认是单例模式,可以用scope属性来设置
(1)单例模式

<bean id="student" class="com.pojo.Student" c:name="zhangsan" c:age="19" scope="singleton"></bean>

prototype是原型模式:每次调用都是新的一个对象

<bean id="student" class="com.pojo.Student" c:name="zhangsan" c:age="19" scope="prototype"></bean>

其它只能在web中使用!!!!

三种自动装配
环境搭配:两个动物,一个zoo

public class Cat {
    public void show(){
        System.out.println("喵喵喵~~~~~~~~");
    }
}
public class Dog {
    public void show(){
        System.out.println("汪汪汪~~~~~~~~");
    }
}
public class Animal {
    private Cat cat;
    private  Dog dog;
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }
}
@Test
public void text(){
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("animalbeans.xml");
    Animal animal = context.getBean("animal", Animal.class);
    animal.getCat().show();
    animal.getDog().show();
}

在这里插入图片描述

第一种:

    <bean id="cat" class="com.bean.Cat"></bean>
    <bean id="dog" class="com.bean.Dog"></bean>

    <bean id="animal" class="com.bean.Animal">
        <property name="cat" ref="cat"></property>
        <property name="dog" ref="dog"></property>
    </bean>

第二种:是byname,会自动查找和自己对象set后面对应的id值
id=’‘cat’’
在animal中是setCat

<bean id="animal" class="com.hujia.bean.Animal" autowire="byName"></bean>

第三种是bytype查找和自己对象属性相同的bean,就是按Bean的Class的类型

<bean id="animal" class="com.hujia.bean.Animal" autowire="byType"></bean>

注解:自动装配
@Autowired是按类型自动转配的,不支持id匹配
需要导入 spring-aop的包!
如果允许对象为null,设置required = false,默认为true
@Autowired(required = false)

@Qualifier
在加上@Autowired的基础上再加上@Qualifier是根据byname的方式进行自动装配

@Resource

  1. @Resource如有指定的name属性,先按该属性进行byName方式查找装配;
  2. 其次再进行默认的byName方式进行装配;
  3. 如果以上都不成功,则按byType的方式自动装配。
  4. 都不成功,则报异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值