@Scope(scopeName ="singleton")// you can define the any other scope like prototype as wellpublicclassNewDoctorimplementsStaff,BeanNameAware {privateString qualification;publicvoidassist() {System.out.println("new doctor is assisting"); }publicStringgetQualification() {return qualification; }publicvoidsetQualification(String qualification) {this.qualification= qualification; } @OverridepublicStringtoString() {return"NewDoctor{"+"qualification='"+ qualification +'\''+'}'; } @OverridepublicvoidsetBeanName(String s) {System.out.println("call for setBeanName"); } @PostConstructpublicvoidpostConstruct(){System.out.println("post construct called"); }}
3. Add this to your spring.xml under the beans tag
Using the javax.annotation.api , we can annotate different methods at different bean life-cycle to execute some code. Example, in NewDoctor class in above example, we have @PostContruct method which is called after the bean is created by spring.
If you declare a prototype bean inside a singleton class, and create 2 different instance of singleton, there prototype bean will also be the same
// example : prototype@Service@Scope("prototype")publicclassWeatherService {String time =LocalDateTime.now().toString();int temp =newRandom().nextInt(60);publicStringgetTodayTemp() {return time +" -> "+ temp; }}// service : singleton@ServicepublicclassUserService { @AutowiredWeatherService weatherService; @AutowiredApplicationContext context; @AutowiredprivateObjectFactory<WeatherService> wFactory;// use this to create seperate beans for each singleton instancepublicStringgetCurrentTemp() {returnweatherService.getTodayTemp(); }publicStringgetCurrentTempDiff() {// not recommended// return context.getBean(WeatherService.class).getTodayTemp();returnwFactory.getObject().getTodayTemp(); }}