1. 程式人生 > 其它 >SpringIOC、DI

SpringIOC、DI

SpringAnnoation

在每個類的上面寫上述一些資訊,就被spring來管理了

package com.ssm.annotation;

import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

@Controller("userController") //代表是Controller層的bean
public class UserController {
    @Resource(name="userService") //將名字是userService的SpringBean注入到userService變數
    private UserService userService;

    public void save(){
        this.userService.save();
        System.out.println("UserController.save()");
    }
}

在resources裡面寫applicationContext.xml的內容如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
">
    <!--
    <context:annotation-config/>
    <bean id="userDao" class="com.ssm.annotation.UserDaoImpl"/>
    <bean id="userService" class="com.ssm.annotation.UserServiceImpl"/>
    <bean id="userController" class="com.ssm.annotation.UserController"/>
-->
    <!--上面的幾行可以替換為:-->
    <context:component-scan base-package="com.ssm.annotation"/> <!--掃描的包:-->

</beans>

Main中使用IOC、DI

package com.ssm.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Anno {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao) applicationContext.getBean("userDao");
        userDao.save();
        UserService userService = (UserService) applicationContext.getBean("userService");
        userService.save();
        UserController userController = (UserController) applicationContext.getBean("userController");
        userController.save();
    }
}