Showing posts with label spring. Show all posts
Showing posts with label spring. Show all posts

Wednesday, 13 November 2019

Spring Annoations - Important Annotations

@Component -- when used above the class , it will create bean of that class which will be injected when the class called with @Autowired annotation.

It can be used in any class or interface.

@Component
public class ProductService { 
...
}

@Service -- same as @Component annotation but can be used only on service layer class (ie. where your business logic goes).


@Service
public class ProductService { 
...
}

@Repository --same as @Component annotation but can be used only on persistence layer (ie. storage , retrieval of data).


@Repository
public interface ProductRepository extends JpaRepository<Product, Long> { 
.....
}

Here "ProductRepository" extends JpaRepository , so it can have all JPA methods like findAll , findById etc . If you want to know more about JpaMethods click here.
"Product" is the entity or table and Long is the auto generated id for entity "Product".



@Controller  --same as @Component annotation but can be used only on presentation layer (ie. where your define your api).


@Controller
@Path("product")
public class ProductResource { 
...
}

@Path is used to specify the api path.


@RequestMapping  -- used in classes on presentation layer for rest API's (GET,POST,PUT and DELETE methods).


@Controller
@Path("product")
public class ProductResource { 

Autowired
ProductService productService;

 @RequestMapping(value = "/id", method = RequestMethod.GET, produces = {
        "application/JSON"
    })
    @ResponseBody
    List<Vendor> getProductDetail() {
        return productService.getProductDetail();
    }

}

RequestMapping(value = "/id", method = RequestMethod.GET, produces = {"application/JSON"}) -Here the request method is GET and return value is of type JSON.


Example for service , controller with repository

ProductService.java

@Component
public class ProductService { 
Autowired
ProductRepository productRepository;

public List<Product> getProductData() throws IOException {

List<Product> productDataList = articleRepository.getProductData();

return productDataList;

}
}

ProductRepository.java

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {

@Query("select p from Product p")
    List<Product> getProductData();
}

ProductResource.java

@Controller
@Path("product")
public class ProductResource { 

Autowired
ProductService productService;

 @RequestMapping(value = "/prod", method = RequestMethod.GET, produces = {
        "application/JSON"
    })
    @ResponseBody
    List<Product> getProductData() {
        return productService.getProductData();
    }

}



@Autowired  -- used to inject the created bean of a class into a reference object.


@Component
public class SampleService { 
Autowired
SampleRepository sampleRepository;

....

}

Here sampleRepository is used to access all the methods with in the  SampleRepository.


@Async  -- used to define a process as seperate thread which is independent of current thread output.The method which uses @Async annotation will run parallely to the method which called it.You can return async method with FUTURE datatype return value or it can be a void method.


@Async
public void loadProductDescription()  {

productRepository.productLoadDescriptionEvict();

}

loadProductDescription -- this method should be called from another class for Async to properly work.Create another class and call this method ,
 so it can run parallel corresponding to the method called it.


@Transactional  -- when you put this annotation above any method it will take care of database management.That is it takes care of open a transaction and commit a transaction , if any error occur it will roll down the transaction and if succeeded , it wil close the transaction.



@Transactional(propagation = Propagation.REQUIRES_NEW)
public void saveOrUpdateArticleInfoVendorList(Long vendor) throws IOException, JAXBException {
List<Product> ProductListForVendorId = productRepository
.findByVendor(vendor);
if (ProductListForVendorId != null) {
for (int j = 0; j < ProductListForVendorId.size(); j++) {
updatProductInfoForEachProduct(ProductListForVendorId.get(j).getProductId());
}
}
}

@Transactional -- this method will be executed as seperate transaction.


@Scheduled -- used for executing time based jobs. If you want a method to execute at particular time , you should annotate the method with @Scheduled annotation. 


@Scheduled(cron = "0 5 * * * ?")
public void productUpdateJob()  {

productRepository.updateProdcutDescriptionFromSource();


}

Here the prodcut description will be updated from given source for 05:00 in the morning.



@Value  -- used to retrieve value stored in application.properties file


@Value("${token.secret.key}")
    private String secretKeyForToken;

Here token.secret.key - is the key present in application.properties.
secretKeyForToken - hold the value for the key specified.

In application.properties file,

token.secret.key = sddfe34343dsdweed@#%


@SpringBootApplication -- this annotation enables the project as spring boot application.

@EnableCaching -- to enable cache in your spring boot application

@EnableAsync -- to enable async in your sping boot application

@EnableRetry -- to enable retry logic in your sping boot application

@EntityScan -- the classes within the specified packages only be scanned for bean creation.

@EnableJpaRepositories -- to enable JPA repository in your sping boot application



@SpringBootApplication
@EnableCaching
@EnableAsync
@EnableRetry
@EntityScan(basePackages = { "com.learnsoftware.productmanagement" })
@EnableJpaRepositories(basePackages = { "com.learnsoftware.productmanagement" })
public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class, args);
}

}

Here the classes within "com.learnsoftware.productmanagement" package only scanned and nly enable for JpaRepository .

@Cacheable -- used to catch the data with the specified cache name.

@CacheEvict -- used to clear the data with the specified cache name.


@Cacheable("ProductCodeAndDescription")
public List<ProductCodeAndDescription> getAllProductCodeAndDescription() {

String qry = "select p.product_id,p.product_description from product p";
Query query = entityManager.createNativeQuery(qry);
List<Object[]> productList = query.getResultList();
ProductCodeAndDescription productCodeAndDescription = null;
List<ProductCodeAndDescription> productCodeAndDescriptionList = new ArrayList<>();
for (Object[] row : productList) {
productCodeAndDescription = new ProductCodeAndDescription();
productCodeAndDescription.setProductId(Long.parseLong(row[0].toString()));
productCodeAndDescription.setProductDescription(row[1].toString());
productCodeAndDescriptionList.add(productCodeAndDescription);

}
return productCodeAndDescriptionList;
}

@CacheEvict(value = "ProductCodeAndDescription", allEntries = true)
public void evictProdcutDetails() {

}

Here "ProductCodeAndDescription" - is the name of the cache.



@retryable -- used to retry the method if fails (due to network issues) for the specified the count.

@Recover  -- if the method fails even after retry attempts , then the annotated with @Recover will be called.

Note: the method should throw the secified exception(SQLException) in order to come to recovery method.

@Retryable(value = { SQLException.class }, maxAttempts = 3, backoff = @Backoff(delay = 1000))
public String getProductResponse(){
...
}

There will be up to 3 retries with a delay of 1000 milliseconds.

@Recover
void recoverMethod(SQLException e, String sql){
...
}



@Scope -- to specify the scope of the bean . By default scope will be singleton. If you want more information about scope click here.

@Component
@Scope("prototype")
public class ProductService {
...
}

JpaRepository annotations

@Repository --same as @Component annotation but can be used only on persistence layer (ie. storage , retrieval of data).


@Modifying -- should use when a query tries to modify your table .

@Query -- query which does transaction goes with this annotation.

@Param -- used to specify the parameters which will be used within the query.


@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {

@Modifying
@Transactional
@Query(value = "UPDATE product SET status=:status WHERE product_id=:productId", nativeQuery = true)
void updateProductStatus(@Param("productId") Long productId, @Param("status") Integer status);

}

Here "productId" and "status" are two parameters which should be specified with colon(:).
nativeQuery = true -- to specify it as native query.
@Transactional -- to specify it as a seperate transaction.

Jersy Rest Api Annotations


@GET  --- should use for retrieving the data.
@Path  -- used to specify the path for the api.
@Produces -- used to specify the return type of the method.
@Consumes -- used to specify the input type of the method
@PUT -- should use for updating the data.
@POST -- should use for inserting or updating the data.
@Delete -- should use for deleting the data.
@PathParam -- used to specify the path related params
@FormDataParam  -- used to specify the file input
@QueryParam  -- used for string or integer input

If you want to know more about Rest API click here.

Unity Top Download

Latest post

An Introduction to Hybris from basics

An Introduction to Hybris from basics:  -- ecommerce site and PCM(Product content Management) solutions. eg. croma website.  -- having sear...

Popular posts