SpringBoot配置非含main类的Controller的注解

刚开始接触SpringBoot,看了一些入门的资料,但是比较有意思的是从最简单的hello world到后面代码都不变了啊23333,要改注解的


不是在含main的类里增加其他包含RequestMapping的controller的类的定义,需要对含main函数的类进行注解,以指向controller类。


方法有两种,一种是用

@ComponentScan(value = {"controller所在包名"})

另一种是用

@SpringBootApplication

例如含RequestMapping的类:

package id0.id1.controller;

import java.util.Date;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/")
public class Ctl {
    @RequestMapping(value="/", method=RequestMethod.GET)
    String home(){
        return "Hello world";
	}
		
	@SuppressWarnings("deprecation")
	@RequestMapping("/now")
	String getTime(){
		return "Current time: " + (new Date()).toLocaleString();
	}
}

要让这个生效,就需要对含main的类增加注解,ComponentScan方式:

package com.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(value = {"com.test.controller"})
@EnableAutoConfiguration
public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        SpringApplication.run(App.class, args);
    }
}

另一种SpringBootApplication方式:

package com.test.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableAutoConfiguration
public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        SpringApplication.run(App.class, args);
    }
}


没有更多推荐了,返回首页