情深忆往缠绵 2023-03-23 10:08 采纳率: 44.6%
浏览 131
已结题

spring如何引用其它bean

问题遇到的现象和发生背景

使用ref有什么前提条件么 ,为什么 我报错

先不排错了,你们写一个完整的调用其它bean的例子,我先弄明白 到底是怎么调用 的,然后再进行排错

javaUser类
package gouzao_zhuru;

public class User {
    private String name;
    private Integer age;
    private char sex;
    
    public User(String name, Integer age, char sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    
    public void Out() {
        System.out.println("name: " + name);
        System.out.println("age: " + age);
        System.out.println("sex: " + sex);
    }
}


javaMain类
package kongzhiqi_zhuru;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import gouzao_zhuru.User;

public class Main{
    public static void main(String[] args) {    
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("UserBean_gouzao_zhuru.xml");
        User user = (User)applicationContext.getBean("User1");
        user.Out();
    }
}


xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx.xsd">
    <bean id="User" class="gouzao_zhuru.User">
        <constructor-arg>
            <value>张三</value>
        </constructor-arg>
        <constructor-arg>
            <value>20</value>
        </constructor-arg>
        <constructor-arg>
            <value></value>
        </constructor-arg>
    </bean>
    <bean id="User1" class="kongzhiqi_zhuru.Main">
        <property name="User" ref="User"></property>
    </bean>
</beans>
报错内容
三月 23, 2023 10:03:53 上午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4783da3f: startup date [Thu Mar 23 10:03:53 CST 2023]; root of context hierarchy
三月 23, 2023 10:03:53 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [UserBean_gouzao_zhuru.xml]
三月 23, 2023 10:03:54 上午 org.springframework.context.support.AbstractApplicationContext refresh
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'User1' defined in class path resource [UserBean_gouzao_zhuru.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'name' of bean class [kongzhiqi_zhuru.Main]: Bean property 'name' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'User1' defined in class path resource [UserBean_gouzao_zhuru.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'name' of bean class [kongzhiqi_zhuru.Main]: Bean property 'name' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1639)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1354)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
    at kongzhiqi_zhuru.Main.main(Main.java:10)
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'name' of bean class [kongzhiqi_zhuru.Main]: Bean property 'name' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    at org.springframework.beans.BeanWrapperImpl.createNotWritablePropertyException(BeanWrapperImpl.java:243)
    at org.springframework.beans.AbstractNestablePropertyAccessor.processLocalProperty(AbstractNestablePropertyAccessor.java:426)
    at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:278)
    at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:266)
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:97)
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:77)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1635)
    ... 13 more


  • 写回答

7条回答 默认 最新

  • Huazie 全栈领域优质创作者 2023-03-23 10:47
    关注

    你直接 获取 User 的Bean

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("UserBean_gouzao_zhuru.xml");
    User user = (User)applicationContext.getBean("User");
    user.Out();
    

    下面这个Main的Bean配置,去除掉, Main是主类,用于你自测运行,无需添加配置

    img

    另外调用指定的带参构造方法给属性注入值,参考如下:

    <bean  id="" class="">
      <constructor-arg  index=""  name=""  value=""  ref="">
        <value></value>
      </constructor-arg>
    </bean>
    

    --- 写了个测试demo:

    package com.demo.bean;
    
    /**
     * @author huazie
     * @version 2.0.0
     * @since 2.0.0
     */
    public class User {
    
        private String name;
        private Integer age;
        private char sex;
    
        public User(String name, Integer age, char sex) {
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
    
        public void printInfo() {
            System.out.println("name: " + name);
            System.out.println("age: " + age);
            System.out.println("sex: " + sex);
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public char getSex() {
            return sex;
        }
    
        public void setSex(char sex) {
            this.sex = sex;
        }
    }
    
    
    
    package com.demo.bean;
    
    /**
     * @author huazie
     * @version 2.0.0
     * @since 2.0.0
     */
    public class Person {
    
        private User user;
    
        public User getUser() {
            return user;
        }
    
        public void setUser(User user) {
            this.user = user;
        }
    }
    
    
    import com.demo.bean.Person;
    import com.demo.bean.User;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    /**
     * @author huazie
     * @version 2.0.0
     * @since 2.0.0
     */
    public class Test {
    
        public static void main(String[] args) {
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
            User user = (User) applicationContext.getBean("User");
            user.printInfo();
    
            Person person = (Person) applicationContext.getBean("Person");
            person.getUser().printInfo();
        }
    }
    
         <bean id="User" class="com.demo.bean.User">
            <constructor-arg>
                <value>张三</value>
            </constructor-arg>
            <constructor-arg>
                <value>20</value>
            </constructor-arg>
            <constructor-arg>
                <value></value>
            </constructor-arg>
        </bean>
        <bean id="Person" class="com.demo.bean.Person">
            <property name="user" ref="User"></property>
        </bean>
    

    运行结果:

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(6条)

报告相同问题?

问题事件

  • 系统已结题 3月31日
  • 已采纳回答 3月23日
  • 修改了问题 3月23日
  • 赞助了问题酬金15元 3月23日
  • 展开全部

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效