spring-boot依赖注入入门

  SpringBoot的实现方式基本都是通过注解实现的,跟Spring注解注入差不多,相关的常见注解有Autowired、Resource、Qualifier、Service、Controller、Repository、Component。

1).Autowired是自动注入,自动从spring的上下文找到合适的bean来注入

2).Resource用来指定名称注入

3).Qualifier和Autowired配合使用,指定bean的名称

4).Service,Controller,Repository分别标记类是Service层类,Controller层类,数据存储层的类,spring扫描注解配置时,会标记这些类要生成bean。

5).Component是一种泛指,标记类是组件,spring扫描注解配置时,会标记这些类要生成bean。

实例:

1.创建对象Test1 和Test2,如下

package com.supre.springboot;
 
import org.springframework.stereotype.Component;
 
@Component
public class Test {
 
	public String test(String str){
		System.out.println("000000000000"+str);
		return "test1"+str;
	}
	
}
package com.supre.springboot;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
@Component
public class Test2 {
 
	@Autowired
	private Test test;
	
	public String test(String str){
		return "test2"+test.test(str);
	}
	
}

2.创建controller类TestController

package com.supre.springboot;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
@Controller
public class TestController {
 
	@Autowired
	private Test test;
	@Autowired
	private Test2 test2;
	
	
	@RequestMapping("/test")
	@ResponseBody
	public String test(String str){
		System.out.println(test2.test(str));
		return test.test(str);
	}
}

3.创建springboot启动类App

package com.supre.springboot;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
 
/**
 * Hello world!
 *
 */
@SpringBootApplication
@RestController
//@ComponentScan(basePackages={"com.supre.springboot"})
public class App{
	@RequestMapping("/")
	public String getHolle(){
		return "HolleWord";
	}
	
    public static void main( String[] args ){
        System.out.println( "Hello World!" );
        SpringApplication.run(App.class, args);
    }
 
}

4.运行启动类App,访问http://localhost:8080/test?str=aaa

注意:后来经研究发现,SpringBoot项目的Bean装配默认规则是根据Application类(SpringBoot项目入口类)所在的包位置从上往下扫描!这个类的位置很关键:如果Application类所在的包为:io.github.project.app,则只会扫描io.github. project.app包及其所有子包,如果service或dao所在包不在io.github. project.app及其子包下,则不会被扫描!

解决方案:

         1.将SpringBoot项目的启动类,放在所以包之上。如Application类放在:“io.github. project”包下,其他类放在“io.github.project.bean”、“io.github.project.controller”、“io.github.project.dao”等。

   2.使用@ComponentScan注解,在springboot的启动类上注解配置,需要扫描的包,例如:

@ComponentScan(basePackages={" io.github.project.app"," io.github.project.bean "})

注意:经测试,依赖注入,不能向static属性注入Spring上下文中的对象。

猜你喜欢

转载自blog.csdn.net/zhizhuodewo6/article/details/81357057