javaSpring uses maven's initial build step java project

Posted by rockintyler on Sun, 05 Jul 2020 16:37:42 +0200

1. Modify in maven projectPom.xmlIntroduce dependencies on spring.
<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">
        <!--  <exclusions>
        </exclusions>  -->

2. Add required profilesApplicationContext.xmlfile

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

<!--     <bean id="..." class="...">
        collaborators and configuration for this bean go here

    <bean id="..." class="...">
        collaborators and configuration for this bean go here
    </bean> -->

    <!-- more bean definitions go here 
    	UserDao ud = new UserDao();
	<bean id="ud" class="com.iflytek.dao.UserDao"></bean>
	<bean id="us" class="com.iflytek.service.UserService">
		<property name="userDao" ref="ud"></property>

Create and initialize required objects by introducing bean s

3. Load other required profiles and dependencies (such as and hibernate dependency)
4. Write java code for testing

For example, in the two bean s configured above, the object us of Userservice and the object ud of UserDao are configured respectively. In the test class, as long as UserService service =Context.getBean("us"),UserService.class;This means that once you get a defined UserService object, there is a property of userDao in the service, and you call the getter method through the service object to get the dao object (because it is private at that time, you want the get to get it explicitly), you can use the method in the dao class.

Attach simple test code

User class

package com.iflytek.domain;

public class User {
	private int id;
	private String name;

	public int getId() {
		return id;

	public void setId(int id) { = id;

	public String getName() {
		return name;

	public void setName(String name) { = name;

	public String toString() {
		return "User [id=" + id + ", name=" + name + "]";

UserService class

package com.iflytek.service;

import com.iflytek.dao.UserDao;

public class UserService {

	private UserDao userDao1;

	public UserDao getUserDao() {
		return userDao1;

	public void setUserDao(UserDao userDao1) {
		this.userDao1 = userDao1;


UserDao class

package com.iflytek.dao;

import com.iflytek.domain.User;

public class UserDao {

	public User getUserById(int i) {
		User user = new User();
		return user;

Test ClassApp.class
package com.iflytek.test;

import org.springframework.context.ApplicationContext;

import com.iflytek.domain.User;
import com.iflytek.service.UserService;

public class App {
public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		//Remove the us object from the IOC container
		UserService service = context.getBean("us", UserService.class);
		User user = service.getUserDao().getUserById(10);
Beginner, everyone communicates, don't want to spray.

Topics: Maven Spring Apache log4j