1. 程式人生 > >如何注入有複雜例項化方法的bean

如何注入有複雜例項化方法的bean

1、使用@Configuration + @Bean

@Configuration
public class ServiceConfig {

	@Bean
	@Scope("prototype")
	public CommonDrawService commonDrawService() {//函式名可以隨便起,不一定commonDrawService
		return RPCClient.getRemoteService(CommonDrawService.class);
	}
}

 

2、FactoryBean

實現FactoryBean介面

public class CrawFactoryBean implements FactoryBean {
    @Override
    public Object getObject() throws Exception {
        return RPCClient.getRemoteService(CommonDrawService.class);
    }

    @Override
    public Class<?> getObjectType() {
        return CommonDrawService.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

applicationContext.xml新增

<bean id="commonDrawService" class="com.shangde.vulcan.management.web.config.CrawFactoryBean"/>

 

3、工廠方法

1)靜態工廠方法

public class CrawFactory {
    public  static CommonDrawService getInstance(){
        return RPCClient.getRemoteService(CommonDrawService.class);
    }
}

applicationContext.xml新增

<bean id="commonDrawService" class="com.shangde.vulcan.front.web.config.CrawFactory" factory-method="getInstance"/>

2)非靜態工廠方法

public class CrawFactory {
    public  CommonDrawService getInstance(){
        return RPCClient.getRemoteService(CommonDrawService.class);
    }
}

applicationContext.xml新增

	<bean id="barFactory" class="com.shangde.vulcan.front.web.config.CrawFactory"/>
	<bean id="commonDrawService" factory-bean="barFactory" factory-method="getInstance"/>