Spring_Bean_静态工厂方式实例化_同时注入属性值_配置xml
文件
话不多说,先上例子
1、创建一个学生类
package com.exec.Ioc.T3;
//学生类
public class Student {
private String name;
private String sex;
private String email;
public void getMessage() {
System.out.println("姓名:"+this.name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
2、创建学生类代理工厂,包含学生类实例化静态方法
package com.exec.Ioc.T3;
//学生类工厂
public class StudentFactory {
//静态代理方法(static)
public static Student getStudent() {
return new Student();
}
}
3、xml
配置文件配置 bean
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- 配置静态代理工厂bean -->
<bean id="studentfactory_bean" class="com.exec.Ioc.T3.StudentFactory"
factory-method="getStudent">
<!-- 可直接为代理的类的属性赋值 -->
<property name="name" value="张三"></property>
</bean>
</beans>
id:
自定义的java类标识
class:
指定当前bean所配置的类,需要完整的包路径
factory-method:
静态的实例化方法,必须为static
<property>:
我们知道这是setter方法的映射,但是我们当前的类并没有name
这个属性,但是由于我们这是静态
方式实例化类,那么我们就可以直接对静态实例化对象的属性进行操作,因为我们已经静态
的代表了对应的类,那么我们就全权代表了他!
4、main
方法测试结果
package com.exec.Ioc.T3;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test_Main {
//main方法测试
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext apc=new ClassPathXmlApplicationContext("T3.xml");
Student student=apc.getBean("studentfactory_bean",Student.class);
student.getMessage();
}
}
5、运行结果:
因此使用静态工厂方式实例化时,我们可以直接对实例化的类属性进行依赖注入进行赋值,因为这是静态实例化,那么我们可以全权代表他,但是在动态代理中就不可以这样操作。