CommandLineRunner and Beans (Spring) -
code question about:
@springbootapplication public class application { private static final logger log = loggerfactory.getlogger(application.class); public static void main(string args[]) { springapplication.run(application.class); } @bean public object test(resttemplate resttemplate) { quote quote = resttemplate.getforobject( "http://gturnquist-quoters.cfapps.io/api/random", quote.class); log.info(quote.tostring()); return new random(); } @bean public resttemplate resttemplate(resttemplatebuilder builder) { return builder.build(); } @bean public commandlinerunner run(resttemplate resttemplate) throws exception { return args -> { quote quote = resttemplate.getforobject( "http://gturnquist-quoters.cfapps.io/api/random", quote.class); log.info(quote.tostring()); }; } } i'm new spring. far understood @bean annotation responsible object saved in ioc container, correct?
if so: first methods @bean collected , then executed?
in example added method test() same run() returns object (random()) instead. result same working commandlinerunner , object.
is there reason why should return commandlinerunner i.e. use syntax run()?
moreover: @ point don't see far advantage move methods container. why not execute it?
thank you!
@configuration classes (@springbootapplication extends @configuration) place spring beans registered. @bean used declare spring bean. method annotated @bean has return object(the bean). default spring beans singletons, once method annotated @bean executed , returns it's value object lives til end of application.
in case
@bean public object test(resttemplate resttemplate) { quote quote = resttemplate.getforobject( "http://gturnquist-quoters.cfapps.io/api/random", quote.class); log.info(quote.tostring()); return new random(); } this produce s singleton bean of type random name 'test'. if try inject (e.g. @autowire) bean of type or name in other spring bean value. not use of @bean annotation, unless want that.
commandlinerunner on other hand special bean lets execute logic after application context loaded , started. makes sense use resttemplate here, call url , print returned value.
not long ago way register spring bean xml. had xml files , bean declarations this:
<bean id="mybean" class="org.company.myclass"> <property name="somefield" value="1"/> </bean> the @configuration classes equivalent of xml files , @bean methods equivalent of <bean> xml element.
so it's best avoid executing logic in bean methods , stick creating objects , setting properties.
Comments
Post a Comment