简单的弹簧注射不起作用

时间:2014-12-26 18:24:02

标签: java spring

我会问一个小问题,我可能没有清楚地遵守代码。我们是否需要在这里做更多的事情。         弹簧注射的例外情况如下......      它对于构造函数arg工作得很好,但不是那么简单......

        can you point mistake here that I am committing...
        Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'triangleType' of bean class [com.raj.spring.core.Triangle]: Bean property 'triangleType' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

        classes ...




        package com.raj.spring.core;

        public class Triangle {

            private String triangleType;

            public Triangle(String triangleType){
                this.triangleType = triangleType;
            }
            public Triangle(){
                System.out.println("constructor");
            }
            public void drawShape() {
                System.out.println(getTriangleType()+" Shape drawn.");
            }

            /**
             * @return the triangleType
             */
            private String getTriangleType() {
                return triangleType;
            }

            /**
             * @param triangleType the triangleType to set
             */
            private void setTriangleType(String triangleType) {
                this.triangleType = triangleType;
            }

        }


        <?xml version="1.0" encoding="UTF-8"?>
    <beans  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-3.0.xsd">
        <bean id="triangle" class="com.raj.spring.core.Triangle">
            <property name="triangleType" value="eqilateral triangle"/>
             <!--<constructor-arg name="triangleType" value="Equilateral triangle"/  -->
        </bean>

    </beans>




        ---------------------------------------
        using in main method----
        -------------------------------

        public static void main(String[] args) {

                ApplicationContext context = new ClassPathXmlApplicationContext("/resources/beans.xml");
                Triangle triangle = context.getBean("triangle",Triangle.class);
                triangle.drawShape();
        }



        It is working fine for constructor-arg but not as simple proprty....

        can you point mistake here that I am committing...

        Many thanks in advance.

1 个答案:

答案 0 :(得分:6)

bean的setter方法必须是public

public void setTriangleType(String triangleType) {

通常,getter方法也应该是public