账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    Java spring getBean
    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
    打赏
    收藏
    点击回答
        全部回答
    • 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.xml is the Spring configuration file where you define your beans. "myBean" is the ID or name of the bean you want to retrieve, and MyClass is the type of the bean.

      Since Spring 4.3, if you're using annotation-based configuration (@Configuration), you can also use ApplicationContext's getBean() 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.

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部