Spring注入方式

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 16:04   2402   0

javabean代码

package com.lin.missyou.simple.hero;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
//@Lazy
public class Diana {
    public Diana(){
        System.out.println("Hello,xxx");
    }
    public void q(){
        System.out.println("Diana Q");
    }
    public void w(){
        System.out.println("Diana W");
    }
    public void e(){
        System.out.println("Diana E");
    }
    public void r(){
        System.out.println("Diana R");
    }
}

1.属性注入

注入方式:

①bytype方式(默认)

②byname方式

package com.lin.missyou.api.v1;

import com.lin.missyou.service.BannerService;
import com.lin.missyou.simple.hero.Diana;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
//@Lazy
@RequestMapping("/v1/banner")
public class BannerController {
    // 属性注入
    @Autowired
    private Diana diana;

    @GetMapping("/test")
    public String test(HttpServletResponse response){
        diana.r();
        return "Hello LittleXiang";
    }
}

2.构造注入(推荐)

package com.lin.missyou.api.v1;

import com.lin.missyou.service.BannerService;
import com.lin.missyou.simple.hero.Diana;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
//@Lazy
@RequestMapping("/v1/banner")
public class BannerController {

    private Diana diana;
    // 构造注入
    @Autowired
    public  BannerController(Diana diana){
        this.diana = diana;
    }


    @GetMapping("/test")
    public String test(HttpServletResponse response){
        diana.r();
        return "Hello LittleXiang";
    }
}

3.set方法注入

package com.lin.missyou.api.v1;

import com.lin.missyou.service.BannerService;
import com.lin.missyou.simple.hero.Diana;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
//@Lazy
@RequestMapping("/v1/banner")
public class BannerController {


    private Diana diana;

    // set注入
    @Autowired
    public void setDiana(Diana diana){
        this.diana = diana;
    }


    @GetMapping("/test")
    public String test(HttpServletResponse response){
        diana.r();
        return "Hello LittleXiang";
    }
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP