SpringIOC、DI

2022/5/22 23:05:27

本文主要是介绍SpringIOC、DI,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

SpringAnnoation

dOdqt.png

在每个类的上面写上述一些信息,就被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();
    }
}



这篇关于SpringIOC、DI的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程