How to resolve ambiguity in Spring constructor injection -
i trying learn constructor injection using spring 4.3.
i having class structure stated below.
@component public class student { private address address; private city city; public student(address address, city city) { this.address = address; this.city = city; } public student(city city, address address) { this.address = address; this.city = city; } public student(city city) { this.city = city; } public student(address address) { this.address = address; } }
java based configuration class:
@configuration @componentscan(basepackages = "com.spring.constructorinjection") public class studentconfiguration { }
client code:
applicationcontext context = new annotationconfigapplicationcontext(studentconfiguration.class); student student = context.getbean(student.class); system.out.println(student.getcity()); system.out.println(student.getaddress());
how can structure java based configuration class assure specific constructor injected?
depends on how want can create bean along profile, able activate @ run time
@configuration @componentscan(basepackages = "com.spring.constructorinjection") public class studentconfiguration { //occasion live @bean @profile("live") public student getstudent(address address, city city){ return new student(address,city); } //occasion test @bean @profile("test") public student getstudent(address address){ return new student(address); } //occasion throwaway @bean @profile("throwaway") public student getstudent(city city){ return new student(city); } }
//make sure address , city annotated component , component scan enabled packages
Comments
Post a Comment