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";
}
}
|