0

All:

I just begin the Spring study, there is one concept confused me so much: The Autowiring.

The question I need to be clear is:

What kind of thing can be autowired? Is it only other beans?

If I define a class Bar:

public class Bar {
    @Autowired
    public String name;
}

I am thinking what if I put a @Autowired annotation to a member variable like String name; and in bean config XML I wrote:

<bean id="bar" class="com.Bar">
    <property name="name" value="Bar" />
</bean>

So many ways to do same thing in Spring confused me so much. ToT. Is there any good trick to clearly remember and tell diff among different ways?

Thanks

Kuan
  • 11,149
  • 23
  • 93
  • 201

2 Answers2

1

Yes, You can only @Autowired Beans. @Autowired is the way of using Dependency Injection in Spring. It is provided for Beans - components wrote once and used many times. There's no sense using DI on String property and I think You get Exception.

tomcyr
  • 641
  • 1
  • 7
  • 13
1

You can't autowire in a String value like you have done.

By writing your XML bean declaration, what you have done is created a singleton instance of Bar with the name field set to the value of 'Bar'.

If you wanted to then use this Bar class elsewhere in your application (say in a class called Foo) you could do this:

public class Foo {
    @Autowired
    private Bar bar;
}

Spring would then inject your instance of Bar into your Foo class.

However because Bar is a singleton by default, no matter how many instances of Bar you autowired into different classes, you would have the same instance of Bar in all of them. So if you try and modify name in one class, it will change for all the other classes.

As a general rule of thumb, if your class has any mutable data (data that will be changed and updated), then your class is not something that you should be declaring for autowiring (because there will only ever be one instance of it inside your Spring application). It works better for things like DAO's and service classes. In answer to your first question, yes you can only autowire instances of classes (beans).

If you need to get a String/Integer/Long/Array/Mutable Data Type value from somewhere, configure a properties file, and read up how to use the org.springframework.beans.factory.config.PropertyPlaceholderConfigurer class with the @Value annotation.

JamesENL
  • 6,400
  • 6
  • 39
  • 64