@NotNull @Min(18) private Integer age;
-
@NotNull
won't allow an empty value -
@Min(18)
won't allow if the age is less than 18 -
!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Getting Started: Handing Form Submission</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <h1>Form</h1> <form action="#" th:action="@{/greeting}" th:object="${greeting}" method="post"> <p>Id: <input type="text" th:field="*{id}" /></p> <p>Message: <input type="text" th:field="*{content}" /></p> <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p> </form> </body> </html> The
th:action="@{/greeting}"
expression directs the form to POST to the/greeting
endpoint, while theth:object="${greeting}"
expression declares the model object to use for collecting the form data. The two form fields, expressed withth:field="*{id}"
andth:field="*{content}"
, correspond to the fields in theGreeting
object above@EnableSchedulingpublic class ScheduledTasks { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 5000) public void reportCurrentTime() { System.out.println("The time is now " + dateFormat.format(new Date())); } }
-
The key components that make this code perform scheduled tasks are the
@EnableScheduling
and@Scheduled
annotations.@EnableScheduling
ensures that a background task executor is created. Without it, nothing gets scheduled.You use
@Scheduled
to configure when a particular method is run.Note: This example uses
fixedRate
, which specifies the interval between method invocations measured from the start time of each invocation. There are other options, likefixedDelay
, which specifies the interval between invocations measured from the completion of the task. You can also use@Scheduled(cron=". . .")
expressions for more sophisticated task scheduling.http://localhost:8080/greeting?name=World"
@RequestParam(value="name",required=false,defaultValue="World")@Entity public class Customer { @Id @GeneratedValue(strategy=GenerationType.AUTO) private long id; private String firstName; private String lastName; private Customer() {} public Customer(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format( "Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } }
Here you have a
Customer
class with three attributes, theid
, thefirstName
, and thelastName
. You also have two constructors. The default constructor only exists for the sake of JPA. You won't use it directly, so it is designated asprivate
.The
Customer
class is annotated with@Entity
, indicating that it is a JPA entity. For lack of a@Table
annotation, it is assumed that this entity will be mapped to a table namedCustomer
.The
Customer
'sid
property is annotated with@Id
so that JPA will recognize it as the object's ID. Theid
property is also annotated with@GeneratedValue
to indicate that the ID should be generated automatically@EnableJpaRepositories public class Application { @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder().setType(H2).build(); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) { LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean(); lef.setDataSource(dataSource); lef.setJpaVendorAdapter(jpaVendorAdapter); lef.setPackagesToScan("hello"); return lef; } @Bean public JpaVendorAdapter jpaVendorAdapter() { HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter(); hibernateJpaVendorAdapter.setShowSql(false); hibernateJpaVendorAdapter.setGenerateDdl(true); hibernateJpaVendorAdapter.setDatabase(Database.H2); return hibernateJpaVendorAdapter; } @Bean public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { return new JpaTransactionManager(entityManagerFactory); }
In the configuration, you need to add the
@EnableJpaRepositories
annotation. This annotation tells Spring Data JPA that it should seek out any interface that extendsorg.springframework.data.repository.Repository
and automatically generate an implementation. By extendingJpaRepository
, yourCustomerRepository
interface transitively extendsRepository
. Therefore, Spring Data JPA will find it and create an implementation for you.Most of the content in
Application
sets up several beans to support Spring Data JPA and the sample:- The
dataSource()
method defines aDataSource
bean, as an embedded database to which the objects are persisted. - The
entityManagerFactory()
method defines aLocalContainerEntityManagerFactoryBean
that is ultimately used to createLocalContainerEntityManagerFactory
a bean that implements theEntityManagerFactory
interface. It is the bean through which JPA operations will be performed. Note that this factory bean'spackagesToScan
property is set to look for entities in the package named "hello". This makes it possible to work with JPA without defining a "persistence.xml" file. - The
jpaVendorAdapter()
method defines a Hibernate-based JPA vendor adapter bean for use by theEntityManagerFactory
bean. - The
transactionManager()
method defines aJpaTransactionManager
bean for transactional persistence.
@Service
public class FacebookLookupService { RestTemplate restTemplate = new RestTemplate(); @Async public Future<Page> findPage(String page) throws InterruptedException { System.out.println("Looking up " + page); Page results = restTemplate.getForObject("http://graph.facebook.com/" + page, Page.class); Thread.sleep(1000L); return new AsyncResult<Page>(results); } }
The class is marked with the
@Service
annotation, making it a candidate for Spring's component scanning to detect it and add it to the application context.The
findPage
method is flagged with Spring's@Async
annotation, indicating it will run on a separate thread. The method's return type isFuture<Page>
instead ofPage
, a requirement for any asynchronous service. This code uses the concrete implementation ofAsyncResult
to wrap the results of the Facebook query.@Configuration @EnableAsync @EnableAutoConfiguration @ComponentScan public class Application implements CommandLineRunner { @Autowired FacebookLookupService facebookLookupService; @Override public void run(String... args) throws Exception { // Start the clock long start = System.currentTimeMillis(); // Kick of multiple, asynchronous lookups Future<Page> page1 = facebookLookupService.findPage("GoPivotal"); Future<Page> page2 = facebookLookupService.findPage("CloudFoundry"); Future<Page> page3 = facebookLookupService.findPage("SpringFramework"); // Wait until they are all done while (!(page1.isDone() && page2.isDone() && page3.isDone())) { Thread.sleep(10); //millisecond pause between each check } // Print results, including elapsed time System.out.println("Elapsed time: " + (System.currentTimeMillis() - start)); System.out.println(page1.get()); System.out.println(page2.get()); System.out.println(page3.get()); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
The
@EnableAsync
annotation switches on Spring's ability to run@Async
methods in a background thread pool.The
@EnableAutoConfiguration
annotation switches on reasonable default behaviors based on the content of your classpath. For example, it looks for any class that implements theCommandLineRunner
interface and invokes itsrun()
method. In this case, it runs the demo code for this guide.public class HelloController { @RequestMapping("/") public String index() { return "Greetings from Spring Boot!"; } }
@RestController
combines@Controller
and@ResponseBody
, two annotations that results in web requests returning data rather than a viewpublic class FacebookLookupService { RestTemplate restTemplate = new RestTemplate(); @Cacheable("hello") public Page findPage(String page) { return restTemplate.getForObject("http://graph.facebook.com/" + page, Page.class); } }
@Cacheable("hello")
. Spring's caching abstraction intercepts the call tofindPage
to check whether it's already been called. If so, Spring's caching abstraction returns the cached copy. Otherwise, it proceeds to invoke the method, store the response in the cache, and then return the results to the caller. - The
相关推荐
### Spring自学笔记-Ioc(控制反转)容器 #### 一、Spring框架简介 Spring框架是一个开源的Java平台,用于构建企业级应用。它提供了一种轻量级的方式来管理应用程序的各种组件和服务,使得开发者能够更容易地构建...
自学Spring所产生的代码,包含IOC、AOP的入门以及进阶,Spring与数据库(MySQL)的交互。(该资源不仅包含我写的代码,一切Spring、aspect、jdbc等所需jar包都俱全,项目导入就能跑起来)
在这个“最小依赖jar不集成spring”的自学练习版本中,我们将专注于Mybatis的核心功能,不涉及与Spring框架的整合。 首先,让我们了解Mybatis的基本构成: 1. **Mybatis核心Jar**:这个版本包含Mybatis框架的核心...
《Spring自学示例项目——深度探索Java开发框架的精髓》 Spring框架,作为Java领域最为广泛应用的开源框架之一,以其强大的功能和灵活的设计理念,深受广大开发者喜爱。本项目"spring-sample"旨在为初学者提供一个...
**Spring 框架概述** Spring 是一个开源的 Java 应用框架,它以其轻量级、模块化和全面的企业级应用支持而闻名。由 Rod Johnson 在 2003 年创立,Spring 旨在简化Java开发,通过依赖注入(Dependency Injection, DI...
【Spring5自学讲义】 Spring框架是Java领域中极为重要的轻量级开源框架,它以其卓越的依赖注入(DI)和面向切面编程(AOP)能力,以及强大的企业级服务支持,成为现代Java应用开发的基石。Spring5是其最新的版本,...
《Spring in Action》是一本备受推崇的Spring框架学习书籍,其深入浅出的讲解方式使得初学者也能快速掌握Spring的...书中不仅涵盖了Spring的基础知识,还包括了最新的Spring框架特性,是一本不可多得的Spring自学资料。
《JavaWeb整合开发完全自学手册》介绍如何整合Struts+Hibernate+Spring+Eclipse进行J2EE开发,所有实例都基于MyEclipseIDE开发,引领读者快速进入基于JavaWeb的J2EE应用领域。《JavaWeb整合开发完全自学手册》主要...
### Spring Security 3.0.1 中文自学教程知识点概览 #### 一、Spring Security 简介 ##### 1.1 Spring Security 是什么? Spring Security 是一款强大的、高度可定制的身份验证与授权框架。它能够帮助开发者保护...
本自学教程集合了多种资源,旨在帮助初学者逐步掌握Spring 3.0 MVC的核心概念,并通过实际项目实例加深理解。 1. **Spring MVC基本概念**:Spring MVC是Spring框架的一部分,负责处理HTTP请求和响应。它遵循模型-...
【Spring MVC 自学教程】 Spring MVC 是一个基于 Model-View-Controller(MVC)设计模式的轻量级 Web 开发框架。它使开发者能够轻松地将业务逻辑、数据处理和用户界面分离,从而提高代码的可维护性和复用性。 **...
《Spring框架技术自学指导》 在当今的Java开发领域,Spring框架无疑是最为流行和广泛使用的框架之一。它以其强大的功能、灵活性以及易用性,深受开发者们的喜爱。本资料集合了多份文档和演示,旨在帮助你系统地学习...
Spring Cloud系列教程 Spring Boot Spring Cloud Stream 和 Kafka案例教程 springcloud生产者与消费者项目实战案例 Spring Cloud 中断路器 Circuit Breaker的应用 配置 Spring Cloud Config Server Spring Cloud ...
本自学文档主要介绍了Spring MVC的基本概念和核心组件,适合初学者掌握其基本工作原理。 1. DispatcherServlet(前端控制器) DispatcherServlet是Spring MVC的入口点,它充当着整个框架的前端控制器角色。在web....
Spring框架是中国Java开发领域中的重要工具,由Rod Johnson在2003年提出的,源于他的著作《Expert One-On-One J2EE Development and Design》中的理念和设计。Spring的诞生是为了应对早期J2EE开发中的一些问题,这些...
前几日自几看spring3.0就这么简单这本书时候留下来的东西,可见本身会有些许问题,但是笔者本身是小白,所以只是更基础适合新手,大神自动略过。ppt
### Spring与Hibernate集成知识点详解 #### 一、Spring与Hibernate集成概述 在现代软件开发中,Spring框架以其强大的依赖注入(DI)和面向切面编程(AOP)能力成为Java领域最受欢迎的企业级应用开发框架之一。而...
SpringBoot是Java开发中的一个流行框架,它简化了Spring应用的初始搭建以及开发过程,让开发者可以更快地投入到实际项目中。这份“自学SpringBoot--入门文档”将引导你逐步了解并掌握SpringBoot的核心概念和技术栈。...
这本"spring+struts+hibernate自学宝典"应该会包含以下内容: 1. **Spring基础**:介绍Spring的核心特性,如IoC容器、AOP、Bean的生命周期管理等。 2. **Spring MVC**:讲解Spring的Web MVC模块,包括...