简体   繁体   中英

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 !!

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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