使用@Configuration
public class User {
private String name;
private Integer age;
User(String name ,Integer age){
this.name = name;
this.age = age;
System.out.println("---------name--------"+name+"---------age--------"+age);
}
User(String name){
this.name = name;
System.out.println("---------name--------"+name);
}
void say(){
System.out.println("-----say----name--------"+name+"-----say----age--------"+age);
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class EntityConfig {
@Bean("user")
public User initUser(){
return new User("yangcai",30);
}
}
@SpringBootApplication
public class StuApplication {
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(StuApplication.class, args);
C c = (C)applicationContext.getBean("user");
c.say();
}
}
使用FactoryBean方式
@Component
public class UserFactoryBean implements FactoryBean {
@Override
public User getObject() throws Exception {
return new User("yangcai",30);
}
@Override
public Class<?> getObjectType() {
return User.class;
}
public void mySay(){
System.out.println("------------------------------------");
}
}
其中可见FactoryBean去创建bean,一共会创建两个对象,一个对象的beanName是userFactoryBean,其中classType是User ,另外一个对象的beanName是&userFactoryBean,其classType是UserFactoryBean