使用Spring容器最簡單的代碼姿式

若是僅僅是爲了測試簡單使用一下Spring的IOC容器,或者研究一下Spring的容器的源碼實現,那麼在搭建Spring工程的時候,不須要複雜的xml配置。Spring3.0以後提供了Java註解配置的方式來啓動Spring容器。下面是最簡單的啓動Spring容器的方式:spring

1.依賴包只須要spring-context便可:apache

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.springexample</groupId>
    <artifactId>spring-ioc</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
    </dependencies>

</project>

2.一個啓動測試類:maven

import com.spring.ioc.SpringConfig;
import com.spring.ioc.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Application {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = context.getBean(UserService.class);
        System.out.println(userService.getSysUser());
    }
}

 

3.一個配置類(@Configuration註解的類至關於一個xml文件),用於掃描和註冊Bean,@ComponentScan註解用於要掃描哪一個包下的Bean(即掃描@Service、@Repository等註解的Bean):ide

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan("com.spring")
@Configuration
public class SpringConfig {

}

 

4.模擬一個業務類,類上加上@Service註解:測試

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    public SysUser getSysUser() {
        return userDao.getSysUser();
    }
}

 

5.模擬Dao服務,類上加上@Repository註解,提供數據訪問服務:this

import org.springframework.stereotype.Repository;

@Repository
public class UserDao {
    public SysUser getSysUser() {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(2);
        sysUser.setUserName("Tom");
        return sysUser;
    }
}

 

6.一個實體類,用於封裝業務數據:spa

public class SysUser {

    private Integer userId;
    private String userName;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Override
    public String toString() {
        return "SysUser{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                '}';
    }
}

 

6.執行測試類Application中的main方法,查看輸出結果:code

SysUser{userId=2, userName='Tom'}
相關文章
相關標籤/搜索