目录
3、根据 Bean 名称 + Bean 类型来获取 Bean(好的解决方法)
假设 Bean 对象是 User,并存储到 Spring 中,注册到 xml 文件中
public class User {
public String sayHi(){
return "hello world";
}
}
下面我将列举获取 Bean 对象的几种方法
下面代码中 context 为 spring (上下文)对象
1、根据名称获取Bean
User user = (User) context.getBean("user");
这种方式获取 Bean 只需要传入名称,即注册到 xml 文件中 Bean 的 id 。
同时我们还需要做一次对象类型强转,因为只传入 id ,getBean() 方法返回的是一个 Object 类型的对象。