0%
三种基本实例化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 {
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-bean
, factory-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>
|