Springboot java configuration method (instance description), springboot instance description
1. Create a User object class.
@Datapublic class User { private String username; private String password; private Integer age;}
2. Create UserDao to simulate database interaction.
Public class UserDao {public List <User> queryUserList () {List <User> result = new ArrayList <User> (); // simulate database query for (int I = 1; I <10; I ++) {User user = new User (); user. setUsername ("username _" + I); user. setPassword ("password" + I); user. setAge (I); result. add (user) ;}return result ;}}
3. Write UserService to implement User data operation business logic.
@ Servicepublic class UserService {@ Autowired // inject the bean object private UserDao userDao in the Spring container; public List <User> queryUserList () {// call the method in userDao for query. Return this. userDao. queryUserList ();}}
4. Compile SpringConfig to instantiate the Spring container.
@ Configuration // This annotation indicates that the class is a spring Configuration, which is equivalent to an xml file. // Configure the scan package. @ ComponentScan (basePackages = "cn. my. springboot. javaconfig ") public class SpringConfig {@ Bean // This annotation indicates that it is a Bean object, which is equivalent to <bean> public UserDao getUserDao () {return new UserDao () in xml (); // The new object is used for demonstration. }}
5. Compile the test method to start the Spring container.
Public class Test {public static void main (String [] args) {// instantiate the Spring container through java configuration. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext (SpringConfig. class); // obtain the bean object UserService userService = context in the Spring container. getBean (UserService. class); // call the method List in the object <User> list = userService. queryUserList (); for (User user: list) {System. out. println (user. getUsername () + "|" user. getPassword () + "|" user. getAge (); // destroy the container context. destroy ;}}}
Test results:
Java code can be used to perfectly replace XML configuration files.
If the structure is unclear, it means that the benevolent sees the wise and the wise sees the wise.
The above spring boot java configuration method (instance description) is all the content shared by the editor. I hope to give you a reference and support for the customer's house.