Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Spring core annotations

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to use Spring core annotations". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use the Spring core annotations.

This is a list of all known Spring core comments.

@ Autowired

We can use the @ Autowired annotation to mark the dependencies that Spring will parse and inject. We can use this comment with a constructor, setter, or field injection.

Constructor injection:

@ RestController public class CustomerController {private CustomerService customerService

@ Autowired public CustomerController (CustomerService customerService) {this. CustomerService = customerService;}}

Second hand injection:

Import organization. Spring frame. Beans. The factory. Comments. Automatic assembly; import organization. Spring frame. The Internet. Bind. Comments. RestController; @ RestController public class CustomerController {private CustomerService customerService; @ Autowired public void setCustomerService (CustomerService customerService) {this. CustomerService = customerService;}}

Field injection:

Import organization. Spring frame. Beans. The factory. Comments. Automatic assembly; import organization. Spring frame. The Internet. Bind. Comments. RestController; @ RestController public class CustomerController {@ Autowired private CustomerService customerService;} for more details, please visit our article on @ Autowired and Spring dependency injection guidelines. @ beans

Bean is a direct simulation of method-level annotations and XML elements. Annotations support some of the properties provided, such as init-method,destroy-method,auto-wiring and name.

You can use annotations in @ Bean annotations @ Configuration or annotated @ Component classes.

The following is a simple example of a @ Bean method declaration:

Import organization. Spring frame. Background. Comments. Beans; imported tissue. Spring frame. Background. Comments. Configuration; imported com. Name of the company. Projectname . Customer. Customer service; imported com. Name of the company. Projectname . Order. OrderService; @ configure public class application {@ bean public CustomerService customerService () {return new CustomerService ();} @ bean public OrderService orderService () {return new OrderService ();}}

The above configuration is equivalent to the following Spring XML:

< beans >

< bean id = "customerService" class = "com.companyname.projectname.CustomerService" />

< bean id = "orderService" class = "com.companyname.projectname.OrderService" />

Read more about annotations in the @ Bean article Spring @ Bean Annotation with Example. @ Qualifier

This comment helps fine-tune comment-based automatic routing. There may be situations where we create multiple bean of the same type and only want to connect to one of the bean using attributes. This can be controlled using @ Qualifier annotations and @ Autowired annotations.

Example: consider using EmailService and SMSService classes to implement a single MessageService interface.

MessageService creates interfaces for multiple messaging service implementations.

Public interface MessageService {public void sendMsg (String message);}

Next, create the implementation: EmailService and SMSService.

The public class EmailService implements MessageService {public void sendMsg (String message) {system. Out. Println (message);}} the public class SMSService implements MessageService {public void sendMsg (String message) {system. Out. Println;}}

It's time to look at the use of @ Qualifier annotations.

The public interface MessageProcessor {public void processMsg (String message);} the public class MessageProcessorImpl implements MessageProcessor {private MessageService messageService; / / setter-based DI @ Autowired @ Qualifier ("emailService") public void setMessageService (MessageService messageService) {this. MessageService = messageService;} / / based on the constructor's DI @ Autowired public MessageProcessorImpl (@ Qualifier ("emailService") MessageService messageService) {this. MessageService = messageService;} public void processMsg (String message) {messageService. SendMsg (message);}} read more about this comment in this article: Spring @ Qualifier Annotation example. @ need

The @ Required annotation of is a method-level annotation and a setter method that is applied to bean.

This comment only indicates that the setter method must be configured to use value dependency injection at configuration time.

For example, the @ Required setter method marks the dependencies we want to populate with XML:

Void setColor (String color) {this is required. Color = color;}

< bean class = "com.javaguides.spring.Car" >

< property name = "color" value = "green" />

Otherwise, the BeanInitializationException will be thrown.

@ value

The Spring @ Value annotation is used to specify default values for variables and method parameters. We can use the @ Value annotation to read the Spring environment variable as well as the system variable.

The Spring @ Value annotation also supports SpEL. Let's look at some examples of using @ Value annotations.

Example: we can use the @ Value annotation to specify default values for class properties.

@ Value ("default DBConfiguration") private String defaultName

The @ Value annotation parameter can be only a string, but spring attempts to convert it to the specified type. The following code works properly and assigns Boolean and integer values to variables.

@ Value ("true") private boolean defaultBoolean

@ Value ("10") private int defaultInt

This demonstrates Spring @ Value-Spring Environment Property

@ Value ("${APP_NAME_NOT_FOUND}") private String defaultAppName

Next, assign the system variable using the @ Value annotation.

@ Value ("${java.home}") private String javaHome; @ Value ("${HOME}") private String homeDir

Spring @ Value-SpEL

@ Value ("# {systemProperties ['java.home']}") private String javaHome; @ depends on the

The @ DependsOn annotation can enforce bean in the Spring IoC container, which initializes one or more bean @ DependsOn annotations before the annotation.

The @ DependsOn annotation can be annotated directly or indirectly with any class using @ Component or with the annotated method @ Bean.

Example: let's create the FirstBean and SecondBean classes. In this example, SecondBean initializes FirstBean before bean.

Public class FirstBean {@ Autowired private SecondBean secondBean;} public class SecondBean {public SecondBean () {system. Out. Println ("SecondBean initialized by Constuctor");}}

Declare the above bean in Java based on the configuration class.

@ configure public class AppConfig {@ Bean ("firstBean") @ DependsOn (value = {"secondBean"}) Public FirstBean firstBean () {return the new FirstBean ();} @ Bean ("secondBean") public SecondBean secondBean () {return new SecondBean ();}} read more about the @ DependsOn comment on Spring-@ DependsOn annotation example. @ lazy

By default, the Spring IoC container creates and initializes all singleton bean when the application starts. We can prevent this preinitialization of singleton bean by using the @ Lazy annotation.

The @ Lazy annotation can be used in any class, as well as directly or indirectly annotated @ Component or with the annotated method @ Bean.

Example: consider that we have two bean-FirstBean and SecondBean. In this example, we explicitly load FirstBean using the @ Lazy annotation.

Public class FirstBean {public void test () {system. Out. Println ("methods of the FirstBean class");} public class SecondBean {public void test () {system. Out. Println ("methods of SecondBean class");}}

Declare the above bean in Java based on the configuration class.

@ configuration public class AppConfig {@ Lazy (value = true) @ bean public FirstBean firstBean () {return new FirstBean ();} @ bean public SecondBean secondBean () {return new SecondBean ();}}

We can see that bean secondBean is initialized by the Spring container, while bean firstBean is explicitly initialized.

Read more about the @ Lazy annotation and provide a complete example-the @ Lazy Annotation example-on Spring. @ look up

The annotated method @ Lookup tells Spring to return an instance of the method return type when we call it.

For more information about this comment, see Spring @ LookUp Annotation. @ Lord

Primary when there are multiple bean of the same type, we use it to give bean a higher priority.

@ part @ main class Car implements Vehicle {} @ part class Bike implements Vehicle {}

@ part class Driver {@ Autowired vehicle;} @ part class Biker {@ Autowired @ Qualifier ("bicycle") vehicle;} read more about this note on Spring-@ Primary Annotation example. @ range

We use the @ Scope annotation to define the scope of the class or the @ Bean definition. It can be a singleton, prototype, request, session, globalSession, or some custom scope. @ Component

For example:

@ part @ Scope (value = ConfigurableBeanFactory. SCOPE_SINGLETON) the public class TwitterMessageService implements MessageService {} @ part @ Scope (value = ConfigurableBeanFactory). SCOPE_PROTOTYPE) the public class TwitterMessageService implements MessageService {} to learn more about the @ Scope annotations Spring @ Scope annotations and Singleton scope examples and Spring @ Scope annotations and prototype scope examples. @ outline

If we want Spring to use the @ Component class or @ Bean method only when a particular configuration file is active, we can use it to mark it @ Profile. We can configure the name of the profile using the annotated value parameter:

@ part @ Profile ("sportDay") class Bike implements Vehicle {}

@ Import

The @ Import annotation indicates one or more @ Configuration class imports.

For example: in a Java-based configuration, Spring provides the @ Import annotation that allows @ Bean definitions to be loaded from another configuration class.

The @ configuration public class ConfigA {@ bean public An a () {returns the new A ();}} @ configuration @ Import (ConfigA). Class) Public class ConfigB {@ bean public B b () {return new B ();}}

Now, when instantiating the context, you don't need to specify both the ConfigA class and the ConfigB class, you just need to explicitly provide ConfigB.

Read more about the @ Import annotation on Spring @ Import Annotation. @ ImportResource

Spring provides an @ ImportResource annotation to load bean from the applicationContext.xml file into ApplicationContext. For example, consider that we have an applicationContext.xml Spring bean configuration XML file on the classpath.

@ configuration @ ImportResource ({"classpath *: applicationContext.xml"}) Public class XmlConfiguration {} read more about this comment through the complete example of Spring @ ImportResource Annotation. @ PropertySource

The @ PropertySource annotation provides a convenient declarative mechanism for adding PropertySource Spring's Eenvironment for use with the @ configuration class.

For example, we read the database configuration from the file config.properties file and use Environment to set these property values to the DataSourceConfig class.

Import organization. Spring frame. Beans. The factory. InitializingBean; import organization. Spring frame. Beans. The factory. Comments. Automatic assembly; import organization. Spring frame. Background. Comments. Configuration; import organization. Spring frame. Background. Comments. PropertySource; import organization. Spring frame. The core. ENV . Environment; @ configuration @ PropertySource ("classpath:config.properties") public class ProperySourceDemo implements InitializingBean {@ Autowired environment ENV; @ overrides public void afterPropertiesSet () throws Exception {setDatabaseConfig ();} private void setDatabaseConfig () {DataSourceConfig config = new DataSourceConfig (); configuration. SetDriver (ENV. GetProperty ("jdbc.driver"); configuration of SetUrl (ENV. GetProperty ("jdbc.url"); configuration of SetUsername (ENV. GetProperty ("jdbc.username"); configuration of SetPassword (ENV. GetProperty ("jdbc.password")); system. Out. The println (configuration. ToString ();}} read more about this comment on Spring @ PropertySource Annotation with Example. @ PropertySources

We can use this annotation to specify multiple @ PropertySource configurations:

@ PropertySources ({@ PropertySource ("classpath:config.properties"), @ PropertySource ("classpath:db.properties")) public class AppConfig {/ /. At this point, I believe you have a better understanding of "how to use Spring core annotations". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report