Spring IOC(控制反转、依赖注入)给类注入属性值的多种方式

前言:接触Spring的人不可能不接触IOC以及AOP,一个是控制反转(IOC)或者说依赖注入,另一个时面向切面编程(AOP)。要说AOP个人觉得现在使用并不是很广泛,毕竟现在的日志插件太多,AOP主要就是在执行事务的的时候可以执行一些操作,打印日志等。
而IOC的思想就是将项目中所有会用到的实体类,放在一个Spring容器中让Spring来管理类的创建或者销毁过程,所以控制的人不再是你,而是Spring容器;以后不再是通过new的方式来创建对象,便可以直接从Spring容器中拿,通过这样的方式来降低耦合度。
比如现在有一个类Student,具体的get和set方法就不明说了

public class Student {
	private int stuNo;
	private String name;
	private String age;
	}
  1. 方式1:根据类的属性赋值,name与属性一一对应
<!-- id唯一标识符  class指定类型 -->
	<bean id="student" class="com.sty.Student">
	<!-- 1、property属性赋值 -->
		<property name="stuNo" value="1"></property>
		<property name="name" value="ls"></property>
		<property name="age" value="25"></property> 
	</bean>
  1. 通过构造器赋值
<!-- 2、通过构造器赋值,基础方式,前提是必须有构造函数并且设置参数的顺序必须和构造函数的参数对应 -->
	<bean id="student" class="com.sty.Student">
		 <constructor-arg value="27"></constructor-arg>
		<constructor-arg value="styty"></constructor-arg>
		<constructor-arg value="21"></constructor-arg> 
	</bean>
  1. 顺序也可以不对应
<!-- 3、如果顺序不对应,可以采用设置属性位置的方式 -->
	<bean id="student" class="com.sty.Student">
		 <constructor-arg value="styty" index="1"></constructor-arg>
		<constructor-arg value="27" index="0"></constructor-arg>
		<constructor-arg value="21" index="2"></constructor-arg> 
	</bean>
  1. 通过对应的属性设置参数
<!-- 4、还可以通过对应的属性设置参数,场景是只对某些属性设值 -->
	<bean id="student" class="com.sty.Student">
		<constructor-arg value="wquwiu" name="name"></constructor-arg>
		<constructor-arg value="27" name="stuNo"></constructor-arg>
		<constructor-arg value="21" name="age"></constructor-arg>
	</bean>
  1. 通过p标签
<bean id="student" class="com.sty.Student" p:age="12" p:name="sty" p:stuNo="213">
</bean>
  1. 在applicationConfig.xml中配置扫描器
<context:component-scan base-package="com.spring" /> 

不过前提是在你的类前面加上@Service,便可以自动扫描
对于最后一种方式,多用来对某些service或者controller类进行配置,主要是在不进行new的时候就可以调用里面的方法;而对于实体类用getBean方式取出来就是一个纯空的对象。这个可以根据自己的需要进行配置
这里写个测试的方法,在主函数调用就行

public static void findStu() {
			//不需要new对象
			ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
			//从IOC获取学生对象,student为配置的bean的id
			Student stu = (Student)context.getBean("student");
			System.out.println(stu);
		}

附上部分结果
在这里插入图片描述
PS:如有错误的观点欢迎指正,也欢迎留言讨论,共同进步,谢谢

发布了93 篇原创文章 · 获赞 26 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_38261445/article/details/91403076