In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this "Spring Notes how to use" article, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Spring Notes how to use" article.
Development of incomplete annotations 1. The first set of annotations
There is no difference in function between this set of annotations about the instantiated creation of objects.
@ Component is used on classes to instantiate Bean
@ Controller is used on web layer classes to instantiate Bean
@ Service is used on service layer classes to instantiate Bean
@ Repository is used on dao layer classes to instantiate Bean
Next, let's analyze the specific code, understand and master them.
First create a UserDao interface and write a random sayHello () method
Public interface UserDao {void sayHello ();}
Then write an interface implementation class UserDaoImpl class, implement the interface method, and output "Hello everyone, I am cabbage ~"
/ / @ Repository (value = "userDao") public class UserDaoImpl implements UserDao {@ Override public void sayHello () {System.out.println ("Hello, I'm cabbage ~");}}
Analysis: adding @ Repository (value = "userDao") to the class means that the instance of this class is put into the spring container. Value = "userDao" is equivalent to the value of the id attribute in the class. When we use annotations, we do not need to specify the package path of the class, so the value of the class attribute is omitted.
Note that using semi-annotated development means configuring the spring file. Unlike before, we need to add a package scan to the configuration file for the annotations to take effect.
Write a test code:
@ Test public void test4 () {ApplicationContext applicationContext = new ClassPathXmlApplicationContext ("applicationContext.xml"); UserService userService = applicationContext.getBean (UserService.class); userService.sayHello ();}
Running result:
2. The second group of notes
The function of this set of annotations is property injection. Let's write a code to see how they are used.
@ Autowired
@ Resource
@ Qulifier: used with @ Autowired
Create an interface UserService and write a method sayHello ()
Public interface UserService {void sayHello ();}
Create an interface implementation class and implement its method. We call the method of the UserDaoImpl class in the method, as follows:
/ / @ Service (value = "userService") public class UserServiceImpl implements UserService {/ / @ Autowired @ Qualifier (value = "userDao") private UserDao userDao;// can omit / / public void setUserDao (UserDao userDao) {/ / this.userDao = userDao;//} @ Override public void sayHello () {userDao.sayHello ();}}
Analysis: note @ Service (value = "userService") to say nothing more, using the same method as the first set of annotations, we introduced private UserDao userDao;, into the class how to inject attributes? You can use @ Autowired+@Qualifier (value = "userDao"), where the value attribute value is equivalent to the ref attribute value in. Happily, we have to write the set method corresponding to the property in the way we use the xml configuration file, but after using the annotation, we don't need to write the set method, isn't it convenient? @ Autowired+@Qualifier (value = "userDao") can be replaced with @ Resource (name= "userDao"), but it is not recommended; @ Autowired+@Qualifier (value = "userDao") can also be replaced with a separate @ Autowired, which means that attributes are injected according to the type. When there are multiple identical types, an error will be reported, so use it carefully.
3. The third group of notes
The function of this set of annotations is string injection, but not just ordinary string injection, let's write a code to see how it is used.
@ Value: perform string injection
@ PropertySource: introduce an external properties file
@ Bean: inject the return value of the method into the spring container
Add the following code to the UserServiceImp class to inject the string content you need using the @ Value annotation
Value ("I am a cabbage") private String name; public void print () {System.out.println (name);}
Write a test code to verify the effect:
@ Test public void test4 () {ApplicationContext applicationContext = new ClassPathXmlApplicationContext ("applicationContext.xml"); UserServiceImpl userService = applicationContext.getBean (UserServiceImpl.class); userService.print ();}
Running result:
This is just one way to use the @ Value annotation. Let's take a look at another way to use it.
First of all, configure a xml file to configure the Druid data source and connect to the MySQL database. The content here is explained very clearly in my Spring column. Friends who do not understand can learn it.
Configure a jdbc.properties file under resources
Jdbc.driver=com.mysql.cj.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/testjdbc.username=rootjdbc.password=0315
Then add @ PropertySource (value = {"classpath:jdbc.properties"}) to the top of the UserServiceImp class, and you don't need it in the spring configuration file. Isn't it convenient to solve it with a single comment?
It should be noted that in the @ PropertySource annotation, by entering the source code, it is found that its attribute value is an array type, which indicates that we can import multiple properties files.
Then write a method in the UserServiceImp class to get the connection object
@ Value ("${jdbc.driver}") private String driverClassName; @ Value ("${jdbc.url}") private String url; @ Value ("${jdbc.username}") private String username; @ Value ("${jdbc.password}") private String password; @ Bean ("dataSource") public DataSource getDataSource () {DruidDataSource dataSource = new DruidDataSource (); dataSource.setDriverClassName (driverClassName); dataSource.setUrl (url) DataSource.setUsername (username); dataSource.setPassword (password); return dataSource;}
Analysis: we use the annotation @ Value to get the value of the properties file, and then configure the connection in the method. Note @ Bean to put the acquired object into the spring container for later use. Its attribute value is equivalent to the id in the bean tag.
Is the configuration successful? Let's write a test code:
@ Test public void test5 () throws SQLException {ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext.xml"); DataSource dataSource = (DataSource) context.getBean ("dataSource"); Connection connection = dataSource.getConnection (); System.out.println (connection);}
Running result:
At this point, we found that there is an extra package scan in the spring configuration file, all alone; can we not use the configuration file? The answer is yes, so let's take a look at fully annotated development.
Full annotation development 1. The first set of annotations
These three notes are not very important, just understand them.
@ Scope: determines whether the object is multiple or singleton
@ PostConstruct: annotation initialization method
@ PreDestroy: Mark the termination method
2. The second group of notes
This set of annotations began to open the door to our full annotation development.
@ Configuration is used to specify that the current class is a Spring configuration class from which annotations are loaded when the container is created.
ComponentScan is used to specify the packages that Spring will scan when initializing the container.
@ PropertySource is used to load the configuration in the .properties file
@ Import is used to import other configuration classes
Using fully annotated development, we first create a main class, SpringConfig
@ Configuration//@ComponentScan (value = {"com.sht"}) public class SpringConfig {private int age = 18; public void print () {System.out.println ("my age is" age + "year");}}
Analysis: @ Configuration tells spring that this is a configuration class, and that the attribute value of @ ComponentScan should fill in the path of the package scan, and its function is the same as that. Here, we can completely eliminate the need for spring configuration files.
Let's test it with code:
@ Test public void test6 () {ApplicationContext context = new AnnotationConfigApplicationContext (SpringConfig.class); SpringConfig config = context.getBean (SpringConfig.class); config.print ();}
Running result:
So the question comes again, if I have other configuration classes, how can I put them in the spring container? At this point, the @ Import annotation is needed.
In the above, I wrote a method in the UserServiceImp class to get the connection objects. I now write them in a UtilGetDataSource class with the following code:
PropertySource (value = {"classpath:jdbc.properties"}) public class UtilGetDataSource {@ Value ("${jdbc.driver}") private String driverClassName; @ Value ("${jdbc.url}") private String url; @ Value ("${jdbc.username}") private String username; @ Value ("${jdbc.password}") private String password; @ Bean ("dataSource") public DataSource getDataSource () {DruidDataSource dataSource = new DruidDataSource () DataSource.setDriverClassName (driverClassName); dataSource.setUrl (url); dataSource.setUsername (username); dataSource.setPassword (password); return dataSource;}}
If we want to use this method, we need to put it in the spring container; with @ Import annotation, its property value is also of an array type, and multiple classes can be introduced
@ Import (UtilGetDataSource.class) public class SpringConfig {}
Finally, write a test class to see if it is correct.
@ Test public void test6 () throws SQLException {ApplicationContext context = new AnnotationConfigApplicationContext (SpringConfig.class); DataSource dataSource = (DataSource) context.getBean ("dataSource"); Connection connection = dataSource.getConnection (); System.out.println (connection);}
Running result:
The above is the content of this article on "how to use Spring Notes". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.