Spring_bean_静态工厂方式实例化_同时注入属性值

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、运行结果:
运行结果
因此使用静态工厂方式实例化时,我们可以直接对实例化的类属性进行依赖注入进行赋值,因为这是静态实例化,那么我们可以全权代表他,但是在动态代理中就不可以这样操作。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值