如果大厂面试官突然问你FactoryBean+Bean你究竟会多少?
很多Java程序员都在绞尽脑汁的想要进互联网大厂,那进入大厂必备的条件也是大家最想知道的,有很多大厂在面试的过程中会提一些不那么常见的问题,所以我们在去大厂面试的时候就需要提前做好准备。
如果大厂面试官突然问你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();
}
}
原文地址:https://blog.51cto.com/14698881/2474918