繁体   English   中英

如何从我的 java bean 中获取名称和 ID?

[英]How can I get the name and id from my java bean?

我正在尝试运行测试 function 以从配置文件中获取我的 bean 的名称和 ID。 到目前为止,我已经尝试了所有我能想到的东西,但没有运气。 我收到大约 40 行我不知道如何阅读的错误。 我确信这很简单,但我只是没有把这些点联系起来。 我怎样才能解决这个问题?

package com.intraedge.spring.springcore;

class Employee {

    private int id;
    private String name;

//  public int getId(int args) {
//      id = args;
//      return id;
//  }

       public void setName(String name){
           this.name = name;
       }

       public String getName(){
           return this.name;
       }


}
package com.intraedge.spring.springcore;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

  public static void main(String[] args) {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("config.xml");
    Employee emp = (Employee)ctx.getBean("emp");
    System.out.println("Name: "+emp.getName(name.value));
//    System.out.println("Id: "+emp.getId(3));
  }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:p="http://www.springframework.org/schema/p" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context.xsd">

  <bean name="emp" class="com.intraedge.spring.springcore.Employee">
    <property name="id">
      <value>20</value>
    </property>

    <property name="name">
      <value>Casandra</value>
    </property>
  </bean>

</beans>

在按照建议更新命名空间后,出现了一个与 bean ID 的 getter/setter 相关的新错误。 我通过添加正确的 getter/setter 函数并从 function 调用中删除任何 arguments 来修复它。

public void setId(int id) {
            this.id = id;
        }

        public int getId() {
            return this.id;
        }

       public void setName(String name){
           this.name = name;
       }

       public String getName(){
           return this.name;
       }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM