Spring 实例化Bean的基本方法

三种基本实例化Bean方法

  • 构造器实例化
  • 静态工厂实例化
  • 实例化工厂实例化
测试用业务类
1
2
3
4
5
6
7
package com.example.service;

public class UserService {
public void test(){
System.out.println("UserService ...");
}
}
测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.example;

import com.example.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App
{
public static void main( String[] args )
{

ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml");
UserService userService = ac.getBean("userService", UserService.class);
userService.test();
}
}

构造器实例化Bean

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="userService" class="com.example.service.UserService"/>
</beans>

静态工厂实例化Bean

  • 要有工厂类和工厂方法,工厂方法负责创建实体类
  • 工厂方法为静态方法
静态工厂
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.example.factory;

import com.example.service.UserService;

/**
* 静态工厂类
*/
public class StaticFactory {

// 创建Bean的静态方法
public static UserService createUserService(){
return new UserService();
}
}

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="userService" class="com.example.factory.StaticFactory" factory-method="createUserService"/>
</beans>

实例化工厂创建Bean

  • 工厂方法为非静态方法
  • 需要配置工厂Bean,并在业务bean中配置 factory-beanfactory-method 属性
实例化工厂
1
2
3
4
5
6
7
8
9
10
11
12
package com.example.factory;

import com.example.service.UserService;

/**
* 实例化工厂类
*/
public class InstanceFactory {
public UserService createUserService(){
return new UserService();
}
}
1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">


<bean id="instanceFactory" class="com.example.factory.InstanceFactory"/>
<bean id="userService" factory-bean="instanceFactory" factory-method="createUserService"/>
</beans>