public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new
ClassPathXmlApplicationContext("spring.xml");
User user = applicationContext.getBean("user", User.class);
System.out.println(user);
}
2.使用conpenent注解的方式
首先在需要依赖注入的bean对象的类中加入@Component注解
@Component
public class User {
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
加入config类,扫描bean所在的包中类的注解
@Configuration
@ComponentScan("com.lx")
public class Config {
}
对对象进行实例化
public static void main(String[] args) {
AnnotationConfigApplicationContext configApplicationContext =
new AnnotationConfigApplicationContext(Config.class);
User user = configApplicationContext.getBean("user", User.class);
System.out.println(user);
}
3.@Bean的方式
在Userbean类里面加入@bean方法获取User
public class UserBean {
@Bean
public User getUser(){
return new User();
}
}
实例化对象
AnnotationConfigApplicationContext configApplicationContext =
new AnnotationConfigApplicationContext(UserBean.class);
User user = configApplicationContext.getBean( User.class);
System.out.println(user);
4.beanDefinition的方式
//获取BeanDefinition的实现类
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
beanDefinition.setBeanClass(User.class);
//将beandefiniton注入到spring中
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.registerBeanDefinition("user",beanDefinition);
context.refresh();
//使用
User user = context.getBean("user", User.class);
System.out.println(user);