您好,登录后才能下订单哦!
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。