Thursday, June 5, 2014

Spring - short note - 1- REST

Creating Rest Services

1.       Create Conroller class which is annotated by :  @Controller;
2.       For get methods:
    @RequestMapping(method = RequestMethod.GET,value = "/rami/{id}/{p}")
    @ResponseBody
    public String home(@PathVariable String id,@PathVariable int p) {
        return "Hello World!"+ id + "----"+p;
    }

Or:
@RequestMapping(method = RequestMethod.GET,value = "/rami")
    @ResponseBody
    public ClassA home3() {
        ClassA a = new ClassA();
        a.setName("ROMA");
        a.setAge(1112222);
        return a;
    }

For POST:
@RequestMapping(method = RequestMethod.POST,value = "/p1/")
     public    @ResponseBody  ClassA home2(@RequestBody ClassA id) {
        return id;
    }

3.      Create main * Spring Boot* :
public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
With following in gradle file:
repositories {
    maven { url "http://repo.spring.io/libs-snapshot" }
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile("org.springframework.boot:spring-boot-starter-web:1.0.2.RELEASE")

}




Working with Config
1. Create Config Class

@Configuration
public class InfiniSpanConfig {

    @Bean(name = "cache1")
    public Cache<String,String> namesCache() {

        Cache<String,String> cache = new DefaultCacheManager().getCache("test",true);
        return cache;
    }
}


2. Add @ComponentScan
3. in case of generic collection type autowiring use @Resource annotation instead of @Autowiring

    @Resource(name="cache1")
    private Cache<String,String> cache;