XML 通過靜態(tài)工廠方法注入 Bean
1. 創(chuàng)建一個 User 類和對應的工廠類 UserFactory
User.java
public class User {
private String name;
private int age;
public User() {
System.out.println("調用User類的無參構造方法");
}
public void sayHello(String name){
System.out.println("hello, " + name + "!");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
UserFactory.java
public class UserFactory {
public static User getInstance(){
return new User();
}
}
2. 在 Spring 配置文件通過靜態(tài)工廠方法注入 User 的 Bean
<bean class="org.daistudy.UserFactory" factory-method="getInstance" id="user2"/>
3. 初始化 Spring 的 IoC 容器巾钉,并獲取 User Bean
User user = (User) context.getBean("user2");
user.sayHello("王五");
4. 適用場景及示例代碼
在一些第三方框架適用過程中,無法直接通過普通構造方法注入趋翻,則不得不適用靜態(tài)工廠方式或實例工廠方法注入睛琳。例如盒蟆,在使用 OkHttp 時踏烙,由于創(chuàng)建 OkHttpClient 對象時需要先創(chuàng)建一個 Builder 來設置相關屬性,此時如果想注入 Bean 則不得不使用靜態(tài)工廠方法注入历等。
OkHttpClientFactory.java
public class OkHttpClientFactory {
public static OkHttpClient getInstance(){
OkHttpClient okHttpClient = new OkHttpClient
.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build();
return okHttpClient;
}
}
靜態(tài)工廠方法注入 OkHttpClient 的 Bean
<bean class="org.daistudy.OkHttpClientFactory" factory-method="getInstance" id="okHttpClient"/>
應用讨惩,下載一個圖片
public class DownloadImage {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
OkHttpClient okHttpClient = (OkHttpClient) context.getBean("okHttpClient");
Request request = new Request.Builder().url("http://pic.netbian.com/uploads/allimg/180826/113958-153525479855be.jpg").get().build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// save image
if (response.isSuccessful()) {
InputStream inputStream = response.body().byteStream();
FileOutputStream fileOutputStream = new FileOutputStream(new File("E:\\1.png"));
byte[] buf = new byte[1024];
int len = 0;
while((len = inputStream.read(buf)) != -1){
fileOutputStream.write(buf, 0, len);
fileOutputStream.flush();
}
fileOutputStream.close();
inputStream.close();
}
}
});
}
}