How setter works inside Spring Framework?

主宰稳场 提交于 2019-11-29 17:56:59

You're confusing fields (or instance variables) with properties.

property is a term coming from the Java Beans specification. A property foo of a bean is data that can be accessed using a getter method called getFoo() (or isFoo() for a boolean) and/or set using a setter method called setFoo().

What these methods do internally, whether they get/set a variable or not, whether the variable is also named foo or anything else, is completely irrelevant. What matters is the name of the getter/setter.

So, when you define your bean and tell Spring to set the property named message, Spring will look for a method called setMessage(). It doesn't care about the private fields of your bean class.

The Spring IoC container also supports setter injection, which is the preferred method of dependency injection in Spring. Setter injection uses the set* methods in a class file to garner property names that are configurable in the spring XML config.

From a configuration standpoint, setter injection is easier to read because the property name being set is assigned as an attribute to the bean, along with the value being injected.

To determine the property names, Spring follows the JavaBeans Specification.

ha9u63ar

First of all, you are mixing up fields with properties - also your property name in the applicationContext.xml is wrong (it should be messageee)

You need to use @Autowired annotation with either:

1) fields i.e. messageee

or

2) setter i.e. setMessage()

If you are thinking "what is that!!???" Read about Spring's basic features with beans and how Spring is capable of taking POJOs (Plain Old Java Objects) to and configure them using the IoC framework. Read about @Autowired here - How does autowiring work in Spring?

Then you should be fine with this:

<bean id="helloWorld" class="com.springframework.HelloWorld">
    <property name="message" value="Hello.. This is Spring Framework example."></property>
</bean>

BTW...good approach for looking into Spring by using the very basic Java stuff....good luck!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!