- 22
- 0
public class test {
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");//读取bean.xml中的内容
Person p = ( Person ) ctx.getBean("person");
p.info();
// Person p = ctx.getBean("person",Person.class);//创建bean的引用对象
// p.info();
}
}
Q:
Person p = ( Person ) ctx.getBean("person"); 为什么 这段 要写写( Person ),不是返回对象了吗
Person p = ctx.getBean("person",Person.class); 这样写又可以
新手 请担待~
- 共 0 条
- 全部回答
-
事与愿违故不知爱 普通会员 1楼
In Java Spring Framework,
getBean()is a method used to retrieve an instance of a bean from the Spring IoC (Inversion of Control) container. The IoC container manages the lifecycle and dependencies of your application components or beans.Here's how you can use
getBean():```java import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainClass { public static void main(String[] args) { // Initialize the Spring context by loading the configuration file ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// Now, get a bean from the context. Let's say we have a bean with id "myBean" and type "MyClass" MyClass myBean = (MyClass) context.getBean("myBean"); // Now you can call methods on this bean myBean.someMethod(); }} ```
In the above example,
applicationContext.xmlis the Spring configuration file where you define your beans."myBean"is the ID or name of the bean you want to retrieve, andMyClassis the type of the bean.Since Spring 4.3, if you're using annotation-based configuration (@Configuration), you can also use
ApplicationContext'sgetBean()method directly without a cast, as it supports generic types:java MyClass myBean = context.getBean(MyClass.class);However, in modern Spring applications, especially those using Spring Boot, direct use of
getBean()is generally discouraged in favor of constructor injection or field injection, which promotes better dependency management and makes code easier to test.
- 扫一扫访问手机版
回答动态

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器更新之后。服务器里面有部分玩家要重新创建角色是怎么回事啊?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题函数计算不同地域的是不能用内网吧?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题ARMS可以创建多个应用嘛?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题在ARMS如何申请加入公测呀?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题前端小程序接入这个arms具体是如何接入监控的,这个init方法在哪里进行添加?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器刚到期,是不是就不能再导出存档了呢?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器的游戏版本不兼容 尝试更新怎么解决?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器服务器升级以后 就链接不上了,怎么办?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器转移以后服务器进不去了,怎么解决?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器修改参数后游戏进入不了,是什么情况?预计能赚取 0积分收益
- 回到顶部
- 回到顶部
