Nandkumar Tekale
Nandkumar Tekale

Reputation: 16158

Spring annotations for factory method

I am using Spring 3.0 for my project, I am having a class MySingletonClass, it is singleton as below :

//@Component("mySingletonClass")
public class MySingletonClass {
    private static MySingletonClass obj = new MySingletonClass();

    public static MySingletonClass getSingleObj() {
        return obj;
    }
}

spring xml bean configuration for this class is as below :

<bean id="mySingletonClass" class="app.MySingletonClass"  factory-method="getSingleObj" />

I was trying to remove bean configuration and use annotation. how do I write annotation for factory method?

Thanks in advance !!

Upvotes: 1

Views: 5516

Answers (2)

pmckeown
pmckeown

Reputation: 4219

Spring component's are automatically created as Singletons.

Declare the annotation @Controller on the class

@Controller
public class MySingletonClass {
}

Then in your Spring Config file, declare like:

<bean id="mySingleton" class="com.package.MySingletonClass">

Then to use in another class you can use Autowiring or Setter/Constructor dependency injection.

@Component 
public class OtherClass {
    @Autowired
    private MySingletonClass mySingleton;
}

Upvotes: 1

chalimartines
chalimartines

Reputation: 5653

Spring creates instances like singleton by default. You can just do.



    @Component("mySingletonClass")
    public class MySingletonClass {
    }


And if you don't change scope your component is singleton.

Upvotes: 2

Related Questions