java - Spring autowire object with value -


suppose have class named someclass takes value in constructor , populates field.

string text; string sometext;  public someclass(string text, string sometext){ this.text = text; this.sometext = sometext; } 

someclass has method creates new object. in java when create new object can instantiate values like

classname variable = new classname(text, sometext); 

and populate fields in classname using constructor

public classname(string text, string sometext){ this.text = text; this.sometext = sometext; } 

but in spring using autowired how can that?

@autowired public classname(someclass someclass){ this.text = someclass.text; this.sometext = someclass.sometext; } 

this wont work. how spring know instance of someclass


update:

i wrong. not thinking in di way. instead of autowiring someclass. had autowire classname.

without di created new object in method of class classname

when using di had autowire in method of class classname

@autowired classname classname; 

i can populate fields directly making fields public

classname.text = text; classname.sometext = sometext; 

and can using javabeans. but how via constructor.

note: there nothing wrong spring config. base scan enabled.

you right in sense spring not automatically know of classes or create required beans. spring not work magic. can use annotations still need tell spring beans create , how create them. @component, @service, @repository, @controller comes play. have here. when want someclass dependency in classname, have explicitly let spring know bean of someclass needs created before can injected dependency in classname, , annotating someclass correct annotation. need <context:component-scan base-package="com.your.package"/> spring resolve annotations correctly before can autowire dependencies.

moreover, have realise fact if someclass constructor arguments depend on dynamic values, won't able create bean right away, , not able inject dependency in classname using @autowired, since spring needs know values during deploy time. if case, i'd prefer using getter setter methods instead in classname instance of someclass.

note: answer taking consideration annotations in spring. can same defining spring beans in xml.


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -