Posts

Showing posts with the label Spring

Spring @Value Annotation Example

Image
In this section we will learn about @Value Annotation. Note  This annotation can be used for injecting values into fields in Spring-managed beans, and it can be applied at the field or constructor/method parameter level.  It is used to assign default values to variables and method arguments.  We can read spring environment variables as well as system variables using @Value annotation.  Spring @Value annotation also supports SpEL. Let’s look at some of the examples of using @Value annotation. 1. Set Default/Static Value We can assign a class member variable with default/static value using  @Value  annotation. // Set static string value @Value ( "Hi, This is a static message." ) private String staticMessage ; // Set default boolean value @Value ( "true" ) private boolean booleanValue ; // Set static integer value @Value ( "234" ) private int integerValue ; 2. Get Value from Properties File @Value  can be used to read values from the properties file. 2.1 Ge

Spring @Autowired Annotation Example

Image
In this section we will learn about @Autowired  Annotation.   We can use the  @Autowired  to mark a dependency which Spring is going to resolve and inject. If  @Autowired  is applied to a field: then the dependency is stored in this  field. a setter: then the setter is invoked, with the parameter that is determined by the same algorithm like for the field dependency  injection. a constructor: then the constructor is invoked with the parameters determined by the same algorithm like for the field dependency injection.     Constructor Injection @RestController public class UserController { private UserService userService; @Autowired public UserController ( UserService userService ) { this . userService = userService; } } Setter Injection @RestController public class UserController { private UserService userService; @Autowired public void setUserService ( UserService userService ) { this . userService = userService; }