Bean注入的三种方式:
(1)接口注入(不推荐)
(2)Setter注入
(3)构造器注入
Spring不去对接口注入作支持,因为通过接口注入总归是要 给对象进行赋值的,是存在耦合的,这违背了spring的初衷
<?xml version="1.0" encoding="UTF-8"?>
<!-- xmlns 命名空间,类似于包名
xml 遵循的标签规范
-->
<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
">
<!-- setter注入 -->
<bean id="student_zhangsan" class="com.app.model.Student">
<property name="name" value="zhangsan" />
<property name="age" value="11" />
<property name="sex" value="male" />
</bean>
<!-- 构造注入 -->
<bean id="student_lisi" class="com.app.model.Student">
<constructor-arg name="name" value="lisi"></constructor-arg>
<constructor-arg name="age" value="13"></constructor-arg>
<constructor-arg name="sex" value="female"></constructor-arg>
</bean>
</beans>
package com.app.pre;
import javax.annotation.PostConstruct;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import com.app.model.Student;
@Component
public class Preload {
@PostConstruct
private void init() {
@SuppressWarnings("resource")
//spring 容器
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//容器管理整所有的bean,BeanFactory提供ApplicationContext获取bean实例的接口
//spring set注入创建对象时调用的是默认构造方法,若显示进行声明构造器,必须存在默认构造方法
Student student1 = (Student) context.getBean("student_zhangsan");
Student student2 = (Student) context.getBean("student_zhangsan");
//单例bean
System.out.print(context.isSingleton("student_zhangsan")+"\r\n");
System.out.print(student1.getName()+"\r\n");
//两者对象的hashcode相等,且是单例bean,说明spring容器创建的这个对象是单例类
System.out.print(student1.hashCode()+"\r\n");
System.out.print(student2.hashCode()+"\r\n");
Student student3 = (Student) context.getBean("student_lisi");
System.out.print(student3.getName()+"\r\n");
System.out.print(student3.getSex()+"\r\n");
}
}
true
zhangsan
1979080261
1979080261
lisi
female