构造方法的方式的属性注入
构造方法:
public Student(Integer age, String name, Cat cat){
this.age = age;
this.name = name;
this.cat = cat;
}
配置文件:
<bean id="Cat" class="com.xiaonuo.demo1.Cat">
<property name="age" value="12" />
</bean>
<bean id="student" class="com.xiaonuo.demo1.Student">
<constructor-arg name="age" value="12"></constructor-arg>
<constructor-arg name="name" value="小诺"></constructor-arg>
<!--因为类里面有引用其他类 所以这把需要ref引用上面的bean-->
<constructor-arg name="cat" ref="Cat"></constructor-arg>
</bean>
Set方法的属性注入
1.给出属性的set方法
2.配置文件
<bean id="Cat" class="com.xiaonuo.demo1.Cat">
<property name="age" value="12" />
</bean>
P名称和C名称空间的属性注入
简介:就是set方法注入和构造方法注入,两种方法都需要引入头链接
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
c 名称:<bean id="student" class="com.xiaonuo.demo1.Student" c:cat-ref="Cat" c:age="21" c:name="小诺" />
p 名称:<bean id="student" class="com.xiaonuo.demo1.Student" p:age="21" p:cat-ref="Cat" p:name="小诺">
spEL表达式的属性注入
<bean id="Cat" class="com.xiaonuo.demo1.Cat">
<property name="age" value="12" />
</bean>
<!--可以直接写值他会自动转换类型 也可以通过调用方法返回值进行赋值-->
<bean id="student" class="com.xiaonuo.demo1.Student" p:age="#{15}" p:cat-ref="Cat" p:name="#{Cat.get()}">
</bean>
集合注入
set方法需要有
构造方法注入同理不需要set方法 但需要构造方法
<property name="array">
<array>
<value>sgw</value>
<value>zly</value>
</array>
</property>
<property name="list">
<list>
<value>sgw</value>
<value>zly</value>
</list>
</property>
<property name="map">
<map>
<entry key="sgw" value="zzz"></entry>
<entry key="zly" value="yyy"></entry>
</map>
</property>
<property name="set">
<set>
<value>yyy</value>
<value>zzz</value>
</set>
</property>
标签注入
1.在配置文件当中,还得要引入一个context约束
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
2.配置组件扫描
3.可以在类开上添加注解
4.使用注解注入属性不需要set方法 也可以在set方法前面添加 那就要在set方法上添加@value("值");
@Component 修改一个类,将这个类交给Spring管理 相当于在配置文件当中配置<bean id="" class=""> 他的三个衍生注解
属性注入
@Value :设置普通属性值
@Autowired:设置对象类型的属性值,直接使用这种方式,是按照类型完全属性注入,不需要在注解上使用id名称
@Qualifier:根据名字来寻找相对应的,和@Autowired连用
@Resource:集合了@Autowired和@Qualifier的功能 和上面的区别可以看这位大佬的博客 https://www.cnblogs.com/fengli9998/p/7472247.html
@PostConstruct:初始化执行的方法
@PreDestroy:销毁实现的方法
@scope:作用范围(单例和多例)