package gaofeng.springboot1;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.Banner.Mode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@SpringBootApplication
public class SpringBoot1App {
public static void main(String[] args) {
// SpringApplication.run(SpringBoot1App.class);
SpringApplication app = new SpringApplication(SpringBoot1App.class);
app.setBannerMode(Mode.OFF);;
app.run();
}
}
@RestController
class Desk{
@Autowired BookInfo bookinfo;
//curl http://127.0.0.1:8080/hello?name=99 -d ""
//curl http://127.0.0.1:8080/hello -d "name=99"
@RequestMapping(value="/hello",method=RequestMethod.POST)
public String hello(String name) {
System.out.println(bookname + " " + bookprice);
System.out.println(bookinfo.name + " " + bookinfo.price);
return "hello,"+name;
}
@Autowired Second second;
@RequestMapping("/hello2")
public String hello2() {
System.out.println("gaofeng ==> /hello2");
return "hello:" + second.getDate();
}
@Value("${book.name}")
String bookname;
@Value("${book.price}")
float bookprice;
}
@Component
@ConfigurationProperties(prefix="book")
class BookInfo{
String name;
float price;
public void setName(String name) {
this.name = name;
}
public void setPrice(float price) {
this.price = price;
}
}
@Component
class Second{
public String getDate() {
return new Date().toLocaleString();
}
}
@Configuration
class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1
corsConfiguration.addAllowedHeader("*"); // 2
corsConfiguration.addAllowedMethod("*"); // 3
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
}
----------application.yaml-----------
server:
port: 8888
context-path: /abc
book:
name: java
price: 55.4
logging:
file: /gf-springboot.log
1、最简单的spring例子。
pom.xml中只依赖spring-context模块,如
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
查看依赖树,看到spring-context又依赖了spring-core,spring-aop,spring-beans,spring-expression
package gaofeng.spring1;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main( String[] args ){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
S1 s1 = context.getBean(S1.class);
context.close();
s1.say();
}
}
package gaofeng.spring1;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("gaofeng.spring1")
public class Config {
}
package gaofeng.spring1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class S1 {
@Autowired
S2 s2 ;
public void say(){
System.out.println("say: " + s2.getData());
}
}
package gaofeng.spring1;
import org.springframework.stereotype.Service;
@Service
public class S2 {
public int getData(){
return 5;
}
}
2、spring的几个标签
2.1 @Resource和@Autowired都可以实现注入。 都可以在成员变量上,也可以在set方法上。
@Autowired只支持byType注入,默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它的required属性为false。
如果我们想使用按照名称(byName)来装配,可以结合@Qualifier注解一起使用。@Autowired @Qualifier("userDao") private UserDao userDao;
@Resource默认按照ByName自动注入。@Resource有两个重要的属性:name和type
2.2 @Service @Scope(value="prototype")//默认是singleton,prototype表示多例
2.3 @Value("ggg") public String name;
2.4 属性文件
@Configuration
@ComponentScan("gaofeng.spring1")
@PropertySource("classpath:config11.properties")
public class Config {
@Autowired Environment env;
@Bean //自动产生name为gao的bean
public String gao(){
return env.getProperty("gaofeng.age");
}
@Bean("gg") //自动产生name为gg的bean
public String gao2(){
return env.getProperty("gaofeng.age");
}
}
2.5 @Autowired List<Base> all; //注入所有实现了Base的类
2.6 @lazy @Service //延迟依赖注入
10、spring boot + spring mvc
http://www.cnblogs.com/shiddong/p/5581906.html
http://blog.csdn.net/u012706811/article/details/52185345
http://blog.csdn.net/yingxiake/article/details/51260302
http://www.open-open.com/lib/view/open1383622135586.html
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.0.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
支持restful
最简的spring boot (restful) curl :8080/desk
@SpringBootApplication //这个标签包含的自动扫描标签,默认扫描当前目录及其子目录
public class App {
public static void main( String[] args ){
SpringApplication.run(App.class, args);
}
}
@RestController
public class Desk {
@RequestMapping(value="/desk")
public String dd(){
return "hello222";
}
}
支持静态web
在 src/main/resources/static 下方一个aa.txt
curl :8080/aa.txt
支持spring mvc
@Controller
public class Desk2 {
@RequestMapping("/desk2")
public String pp(){//spring mvc
System.err.println("hh");
return "hello2";
}
@RequestMapping("/desk3")
public String pp(Model model){//spring mvc
System.err.println("hh2");
model.addAttribute("name", "gaofeng");
return "hello2";
}
}
在src/main/resources/templates/下创建thymeleaf模板文件hello2.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'">mm</p>
</body>
</html>
修改tomcat端口
在工程根目录下增加application.properties server.port=80
用户登录
@RequestMapping("pkg")
public String getpkgs(String user, HttpSession session) {
session.setAttribute("user", user);//登录时,把用户信息记录在session中
return "pkg";
}
@RequestMapping("/now")
String hehe(HttpSession session) {
//用户访问页面时,判断用户有没有登录,用户名是什么。
//当然好一点的做法是在拦截器中判断用户是否已经登录,没有登录就跳转到登录页面。
System.err.println("user: " + session.getAttribute("user") );
return "现在时间4:" + new Date().toLocaleString();
}
7、单元测试
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=SpringBoot1App.class)
@WebAppConfiguration
public class TestDesk {
MockMvc mvc;
@Autowired
WebApplicationContext webApplicationConnect;
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationConnect).build();
}
@Test
public void test() throws Exception {
String uri = "/hello2";
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri)).andReturn();
int status = mvcResult.getResponse().getStatus();
String content = mvcResult.getResponse().getContentAsString();
System.out.println(status + " " + content);
}
}
8、springboot + jersey
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
</dependencies>
@SpringBootApplication
public class SpringBoot2App {
public static void main(String[] args) {
SpringApplication.run(SpringBoot2App.class);
}
}
@Component
class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
//注册类的方式
register(Desk.class);
//注册包的方式
// packages("gaofeng.springboot2");
}
}
//重要 Desk类必须是public的,类前面必须有@Path
@Component
@Path("/")
public class Desk{
//curl http://127.0.0.1:8080/hello?name=99 -d ""
//curl http://127.0.0.1:8080/hello -d "name=99"
@Path("hello")
@GET
public String hello(@QueryParam(value = "name") String name) {
return "hello,"+name;
}
}