您好,登錄后才能下訂單哦!
FactoryBean+Bean
package com.example.demo10.entity;
//實體
public class Stu {
String name;
public Stu(String name) {
this.name = name;
}
public Stu() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.example.demo10.factory;
import com.example.demo10.entity.Stu;
import org.springframework.beans.factory.FactoryBean;
//創建一個Stu場子
public class StuFactory implements FactoryBean<Stu> {
@Override
public Class<?> getObjectType() {
return Stu.class;
}
@Override
public boolean isSingleton() {
return false;
}
@Override
public Stu getObject() throws Exception {
return new Stu();
}
}
package com.example.demo10.configuration;
import com.example.demo10.factory.StuFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class StuConfiguration {
//創建場子Bean
//這里要注意返回的是場子對象,但是正真獲取的是Stu對象
@Bean
public StuFactory stuFactory(){
return new StuFactory();
}
}
package com.example.demo10;
import com.example.demo10.entity.Stu;
import com.example.demo10.factory.StuFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class Demo10Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Demo10Application.class, args);
//獲取場子里面的產品
Stu stu1 = context.getBean("stuFactory", Stu.class);
Stu stu2 = context.getBean("stuFactory", Stu.class);
System.out.println(stu1.getClass().getName());
System.out.println(stu1.hashCode());
System.out.println(stu2.getClass().getName());
System.out.println(stu2.hashCode());
//獲取工廠自己
StuFactory stuFactory = context.getBean("&stuFactory", StuFactory.class);
System.out.println(stuFactory.getClass().getName());
context.close();
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。