@SpringBootApplication

@SpringBootApplication encapsulates @Configuration@EnableAutoConfiguration, and @ComponentScan annotations with their default attributes.

@EnableAutoConfiguration

@EnableAutoConfiguration, as its name says, enables auto-configuration. It means that Spring Boot looks for auto-configuration beans on its classpath and automatically applies them.

Note, that we have to use this annotation with @Configuration:

@Configuration
@EnableAutoConfiguration
class VehicleFactoryConfig {}

Auto-Configuration Conditions

Usually, when we write our custom auto-configurations, we want Spring to use them conditionally. We can achieve this with the annotations in this section.

We can place the annotations in this section on @Configuration classes or @Bean methods.

In the next sections, we’ll only introduce the basic concept behind each condition. For further information, please visit this article.

1. @ConditionalOnClass and @ConditionalOnMissingClass

Using these conditions, Spring will only use the marked auto-configuration bean if the class in the annotation’s argument is present/absent:

@Configuration
@ConditionalOnClass(DataSource.class)
class MySQLAutoconfiguration {
    //...
}

2. @ConditionalOnBean and @ConditionalOnMissingBean

We can use these annotations when we want to define conditions based on the presence or absence of a specific bean:

@Bean
@ConditionalOnBean(name = "dataSource")
LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    // ...
}

3. @ConditionalOnProperty

With this annotation, we can make conditions on the values of properties:

@Bean
@ConditionalOnProperty(
    name = "usemysql", 
    havingValue = "local"
)
DataSource dataSource() {
    // ...
}

4. @ConditionalOnResource

We can make Spring to use a definition only when a specific resource is present:

@ConditionalOnResource(resources = "classpath:mysql.properties")
Properties additionalProperties() {
    // ...
}

5. @ConditionalOnWebApplication and @ConditionalOnNotWebApplication

With these annotations, we can create conditions based on if the current application is or isn’t a web application:

@ConditionalOnWebApplication
HealthCheckController healthCheckController() {
    // ...
}

6. @ConditionalExpression

We can use this annotation in more complex situations. Spring will use the marked definition when the SpEL expression is evaluated to true:

@Bean
@ConditionalOnExpression("${usemysql} && ${mysqlserver == 'local'}")
DataSource dataSource() {
    // ...
}

7. @Conditional

For even more complex conditions, we can create a class evaluating the custom condition. We tell Spring to use this custom condition with @Conditional:

@Conditional(HibernateCondition.class)
Properties additionalProperties() {
    //...
}

@EnableAutoConfiguration

The @EnableAutoConfiguration annotation enables Spring Boot to auto-configure the application contextTherefore, it automatically creates and registers beans based on both the included jar files in the classpath and the beans defined by us.

For example, when we define the spring-boot-starter-web dependency in our classpath, Spring boot auto-configures Tomcat and Spring MVC. However, this auto-configuration has less precedence in case we define our own configurations.

The package of the class declaring the @EnableAutoConfiguration annotation is considered as the default. Therefore, we should always apply the @EnableAutoConfiguration annotation in the root package so that every sub-packages and class can be examined:

@Configuration
@EnableAutoConfiguration
public class EmployeeApplication {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(EmployeeApplication.class, args);
        // ...
    }
}

Furthermore, the @EnableAutoConfiguration annotation provides two parameters to manually exclude any parameter:

We can use exclude to disable a list of classes that we do not want to be auto-configured:

@Configuration
@EnableAutoConfiguration(exclude={JdbcTemplateAutoConfiguration.class})
public class EmployeeApplication {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(EmployeeApplication.class, args);
        // ...
    }
}

We can use excludeName to define a fully qualified list of class names that we want to exclude from the auto-configuration:

@Configuration
@EnableAutoConfiguration(excludeName = {"org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration"})
public class EmployeeApplication {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(EmployeeApplication.class, args);
        // ...
    }
}

Since Spring Boot 1.2.0, we can use the @SpringBootApplication annotation, which is a combination of the three annotations @Configuration, @EnableAutoConfiguration, and@ComponentScan with their default attributes:

@SpringBootApplication
public class EmployeeApplication {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(EmployeeApplication.class, args);
        // ...
    }
}

Reference :

@ComponentScan in SpringBoot

  • First @Configurations are scanned before @Components by @ComponentScan
  • Hence configurations are annotated with @ComponentScan to direct Spring to those Components that are required for the @Configuration
  • Secondly, all the Components are scanned

While developing an application, we need to tell the Spring framework to look for Spring-managed components. @ComponentScan enables Spring to scan for things like configurations, controllers, services, and other components we define.

In particular, the @ComponentScanannotation is used with @Configuration annotation to specify the package for Spring to scan for components:

@Configuration
@ComponentScan
public class EmployeeApplication {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(EmployeeApplication.class, args);
        // ...
    }
}

Alternatively, Spring can also start scanning from the specified package, which we can define using basePackageClasses() or basePackages()If no package is specified, then it considers the package of the class declaring the @ComponentScan annotation as the starting package:

package com.baeldung.annotations.componentscanautoconfigure;

// ...

@Configuration
@ComponentScan(basePackages = {"com.baeldung.annotations.componentscanautoconfigure.healthcare",
  "com.baeldung.annotations.componentscanautoconfigure.employee"},
  basePackageClasses = Teacher.class)
public class EmployeeApplication {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(EmployeeApplication.class, args);
        // ...
    }
}

In the example, Spring will scan the healthcare and employee packages and the Teacher class for components.

Spring searches the specified packages along with all its sub-packages for classes annotated with @ConfigurationAdditionallythe Configuration classes can contain @Bean annotations, which register the methods as beans in the Spring application context. After that, the @ComponentScan annotation can auto-detect such beans:

@Configuration
public class Hospital {
    @Bean
    public Doctor getDoctor() {
        return new Doctor();
    }
}

Furthermore, the @ComponentScan annotation can also scan, detect, and register beans for classes annotated with @Component, @Controller, @Service, and @Repository.

For example, we can create an Employee class as a component which can be scanned by the @ComponentScan annotation:

@Component("employee")
public class Employee {
    // ...
}

Note : ComponentScan is not ment to scan all the @Componets and @Beans, it is ment to register a group of Packages from which it can find its configuration files and @EnableAutoConfiguration annotation should be used that the scan all class purpose, hence to be put in root class. And @EnableAutoConfiguration comes by default with @SpringBootApplication

ComponentScan Without Arguments

With Spring, we use the @ComponentScan annotation along with the @Configuration annotation to specify the packages that we want to be scanned. @ComponentScan without arguments tells Spring to scan the current package and all of its sub-packages.

Let’s say we have the following @Configuration in com.baeldung.componentscan.springapp package:

@Configuration
@ComponentScan
public class SpringComponentScanApp {
    private static ApplicationContext applicationContext;

    @Bean
    public ExampleBean exampleBean() {
        return new ExampleBean();
    }

    public static void main(String[] args) {
        applicationContext = 
          new AnnotationConfigApplicationContext(SpringComponentScanApp.class);

        for (String beanName : applicationContext.getBeanDefinitionNames()) {
            System.out.println(beanName);
        }
    }
}

In addition, we have the Cat and Dog components in com.baeldung.componentscan.springapp.animals package:

package com.baeldung.componentscan.springapp.animals;
// ...
@Component
public class Cat {}
package com.baeldung.componentscan.springapp.animals;
// ...
@Component
public class Dog {}

Finally, we have the Rose component in com.baeldung.componentscan.springapp.flowers package:

package com.baeldung.componentscan.springapp.flowers;
// ...
@Component
public class Rose {}

The output of the main() method will contain all the beans of com.baeldung.componentscan.springapp package and its sub-packages:

springComponentScanApp
cat
dog
rose
exampleBean

Note that the main application class is also a bean, as it’s annotated with @Configuration, which is a @Component.

We should also note that the main application class and the configuration class are not necessarily the same. If they are different, it doesn’t matter where we put the main application class. Only the location of the configuration class matters, as component scanning starts from its package by default.

Finally, note that in our example, @ComponentScan is equivalent to:

@ComponentScan(basePackages = "com.baeldung.componentscan.springapp")

The basePackages argument is a package or an array of packages for scanning.

2.2. Using @ComponentScan in a Spring Boot Application

The trick with Spring Boot is that many things happen implicitly. We use the @SpringBootApplication annotation, but it’s a combination of three annotations:

@Configuration
@EnableAutoConfiguration
@ComponentScan

Let’s create a similar structure in com.baeldung.componentscan.springbootapp package. This time the main application will be:

package com.baeldung.componentscan.springbootapp;
// ...
@SpringBootApplication
public class SpringBootComponentScanApp {
    private static ApplicationContext applicationContext;

    @Bean
    public ExampleBean exampleBean() {
        return new ExampleBean();
    }

    public static void main(String[] args) {
        applicationContext = SpringApplication.run(SpringBootComponentScanApp.class, args);
        checkBeansPresence(
          "cat", "dog", "rose", "exampleBean", "springBootComponentScanApp");

    }

    private static void checkBeansPresence(String... beans) {
        for (String beanName : beans) {
            System.out.println("Is " + beanName + " in ApplicationContext: " + 
              applicationContext.containsBean(beanName));
        }
    }
}

All other packages and classes remain the same, we’ll just copy them to the nearby com.baeldung.componentscan.springbootapp package.

Spring Boot scans packages similarly to our previous example. Let’s check the output:

Is cat in ApplicationContext: true
Is dog in ApplicationContext: true
Is rose in ApplicationContext: true
Is exampleBean in ApplicationContext: true
Is springBootComponentScanApp in ApplicationContext: true

The reason we’re just checking the beans for existence in our second example (as opposed to printing out all the beans), is that the output would be too large.

This is because of the implicit @EnableAutoConfiguration annotation, which makes Spring Boot create many beans automatically, relying on the dependencies in pom.xml file.

3. @ComponentScan With Arguments

Now let’s customize the paths for scanning. For example, let’s say we want to exclude the Rose bean.

3.1. @ComponentScan for Specific Packages

We can do this a few different ways. First, we can change the base package:

@ComponentScan(basePackages = "com.baeldung.componentscan.springapp.animals")
@Configuration
public class SpringComponentScanApp {
   // ...
}

Now the output will be:

springComponentScanApp
cat
dog
exampleBean

Let’s see what’s behind this:

  • springComponentScanApp is created as it’s a configuration passed as an argument to the AnnotationConfigApplicationContext
  • exampleBean is a bean configured inside the configuration
  • cat and dog are in the specified com.baeldung.componentscan.springapp.animals package

All of the above-listed customizations are applicable in Spring Boot too. We can use @ComponentScan together with @SpringBootApplication and the result will be the same:

@SpringBootApplication
@ComponentScan(basePackages = "com.baeldung.componentscan.springbootapp.animals")

3.2. @ComponentScan with Exclusions

Another way is to use a filter, specifying the pattern for the classes to exclude:

@ComponentScan(excludeFilters = 
  @ComponentScan.Filter(type=FilterType.REGEX,
    pattern="com\\.baeldung\\.componentscan\\.springapp\\.flowers\\..*"))

We can also choose a different filter type, as the annotation supports several flexible options for filtering the scanned classes:

@ComponentScan(excludeFilters = 
  @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Rose.class))

4. The Default Package

We should avoid putting the @Configuration class in the default package (i.e. by not specifying the package at all). If we do, Spring scans all the classes in all jars in a classpath, which causes errors and the application probably doesn’t start.

Create your own annotation

Why to create annotation ?

  • For documentation purpose – Help the developers reading it understand
  • As an input to java source code processor

Libraries that use their own annotations ?

  • Spring & Spring Boot
  • Jackson JSON toolkit
  • Hibernate

Example of where annotations can be used :

Sample Annotation

Where annotation can be used

As displayed above it can be used for class, method, arguments,variables etc.

Providing values to annotation

  • Custome Annotation 2 elements
  • Class CustomeAnnotationExample1 uses the annotation and provides value to it
  • If not value is provided in below example, it will give compilation error since default value for that annotation is not provided

Providing default values to annotation

  • Now we don’t need to provide values to annotation anymore

Specifying where the annotation can be used

As you can see in the above screenshot

@Target annotation can be used to specify where CustomeAnnotation1 annotation can be sed

  • Used on Another annotation
  • Used on Constructor
  • Used on Local variable
  • Used on Method
  • Used on Package
  • Used on Parameter
  • Used on Type (Class)
  • Used on Type Parameter

Example :

The compiler gives warning that it cannot be used at that location because the @Target type for the annotation is TYPE i.e allowed only on classes

Example of using the value of Annotation in class

Output :

Reference :

SpringBoot starters

Most common spring boot starter dependency

  • Spring Boot starters can help to reduce the number of manually added dependencies just by adding one dependency
  • spring-boot-starter-web
    • RESTful web application
    • Spring MVC
    • Tomcat as default container
  • spring-boot-starter-security
    • Spring security
  • spring-boot-starter-actuator
  • spring-boot-starter-data-jdbc
  • spring-boot-start-log4j2
  • spring-boot-starter-test
  • spring-boot-starter-web-services
    • For SOAP Web Services
  • spring-boot-starter-thymeleaf
    • MVC webapplication with thymleaf

Scope of Bean is SpringBoot

There are five types of spring bean scopes:

  1. singleton – Default –only one instance of the spring bean will be created for the spring container. This is the default spring bean scope. While using this scope, make sure bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues.
  2. prototype – A new instance will be created every time the bean is requested from the spring container.
  3. request – This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.
  4. session – A new bean will be created for each HTTP session by the container.
  5. global-session – This is used to create global session beans for Portlet applications.

Spring Bean Singleton and Prototype Scope

Spring bean singleton and prototype scopes can be used in standalone spring apps. Let’s see how we can easily configure these scopes using @Scope annotation.

Let’s say we have a java bean class.

package com.journaldev.spring;

public class MyBean {

	public MyBean() {
		System.out.println("MyBean instance created");
	}

}

Let’s define the spring configuration class where we will define the method to get MyBean instance from spring container.

package com.journaldev.spring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class MyConfiguration {
	
	@Bean
	@Scope(value="singleton")
    public MyBean myBean() {
		return new MyBean();
	}
	
}

Note that singleton is default scope, so we can remove @Scope(value="singleton") from above bean definition.

Now let’s create a main method and test the singleton scope.


package com.journaldev.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MySpringApp {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.register(MyConfiguration.class);
		ctx.refresh();

		 MyBean mb1 = ctx.getBean(MyBean.class);
		 System.out.println(mb1.hashCode());

		 MyBean mb2 = ctx.getBean(MyBean.class);
		 System.out.println(mb2.hashCode());

		ctx.close();
	}

}

When above program is executed, we will get output like below.

MyBean instance created
867988177
867988177

Notice that both MyBean instances have same hashcode and the constructor is called once once, it means that spring container is returning the same instance of MyBean always.

Now let’s change the scope to prototype.


@Bean
@Scope(value="prototype")
public MyBean myBean() {
	return new MyBean();
}

This time we will get following output when main method is executed.


MyBean instance created
867988177
MyBean instance created
443934570

Reference :

JournalDev

What is dependency Injection (DI) and Inversion of Control (IOC)

  • Dependency Injection (DI) is a software design pattern.
  • According to DI all the components should be as independent as possible with other Java classes
  • This increases the possibility of reusing the class and testing them independently
  • In the above example if class A needs Object of class B and class C, Class A has to create objects of class B and class C. But in IOC using DI, the object of B and C is created by the Spring container for class A
  • So in nutshell rather than A configuring itself by creating object for class B and C, class B and class C object are configured by the container

Advantages :

  • IOC makes it loosely coupled
  • We provided the Information to spring container by XML or by annotations
  • There are two ways of injecting dependency
    • Constructor Injection
    • Dependency Injection

  • Autowiring feature of the spring framework enables you to inject object dependency implicitly. It internally uses setter or constructor injection.

Angular Architecture

The Eight main building blocks of an Angular application:

  • Modules
  • Components
  • Templates
  • Metadata
  • Data binding
  • Directives
  • Services
  • Dependency injection

Modules

Every Angular app has a root module, conventionally named AppModule, which provides the bootstrap mechanism that launches the application. An app typically contains many functional modules.

// app.module.tsimport { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

If we want to use another custom Angular module, then we need to register that module inside the app.module.ts file. Organizing your code into distinct functional modules helps in managing the development of complex applications, and in designing for re usability.

Angular libraries

Angular ships as a collection of JavaScript modules. You can think of them as library modules.

Each Angular library name begins with the @angular prefix.

You install them with the npm package manager and import parts of them with JavaScript importstatements.

For example, import Angular’s Component decorator from the @angular/core library like this:

import { Component } from '@angular/core';

You also import Angular modules from Angular libraries using JavaScript import statements:

import { BrowserModule } from '@angular/platform-browser';

In the example of the simple root module above, the application module needs material from within that BrowserModule. To access that material, add it to the @NgModule metadata imports like this.

imports:      [ BrowserModule ],

In this way you’re using both the Angular and JavaScript module systems together.

Components

Every Angular project has at least one component, the root component and root component connects the component hierarchy with a page document object model (DOM). Each component defines the class that contains application data and logic, and it is associated with the HTML template that defines the view to be displayed in a target app.A component controls a patch of screen called a view.

The @Component decorator identifies the class immediately below it as the component and provides the template and related component-specific metadata.

// app.component.ts@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

Templates

The angular template combines the HTML with Angular markup that can modify HTML elements before they are displayed. Template directives provide program logic, and binding markup connects your application data and the DOM. There are two types of data binding.

  • Event binding lets your app respond to user input in the target environment by updating your application data.
  • Property binding lets you interpolate values that are computed from your application data into the HTML.
<div style="text-align:center">
<h1>
{{2 | power: 5}}
</h1>
</div>

In the above HTML file, we have used a template. We have also used the pipe inside the template to transform the values to the desired output.

Metadata

Metadata tells Angular how to process a class.It is used to decorate the class so that it can configure the expected behavior of a class. Decorators are the core concept when developing with Angular (versions 2 and above). The user can use metadata to a class to tell Angular app that AppComponent is the component. Metadata can be attached to the TypeScript using the decorator.

// app.component.ts@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

Here is the @Component decorator, which identifies the class immediately below it as a component class.

The @Component decorator takes a required configuration object with the information Angular needs to create and present the component and its view.

Here are a few of the most useful @Component configuration options:

  • selector: CSS selector that tells Angular to create and insert an instance of this component where it finds a <app-root>tag which is Parent Component.
  • templateUrl: module-relative address of this component’s HTML template.
  • providers: array of dependency injection providers for services that the component requires.

The metadata in the @Component tells Angular where to get the major building blocks you specify for the component.

The template, metadata, and component together describe a view.

Apply other metadata decorators in a similar fashion to guide Angular behavior. @Injectable@Input, and @Output are a few of the more popular decorators.

Data binding

Data binding plays an important role in communication between a template and its component.

Data binding is also important for communication between parent and child components.Angular allows defining communication between a component and the DOM, making it very easy to define interactive applications without worrying about pulling and pushing the data.

From the Component to the DOM

Interpolation: {{ value }}: Interpolation adds the value of the property from the component.

<p>Name: {{ student.name }}</p>
<p>College: {{ student.college }}</p>

Property binding: [property]=”value”

With property binding, a value is passed from a component to a specified property, which can often be a simple html attribute.

<input type="text" [value]="student.name" />
<input type="text" [value]="student.college" />

Event binding: (Event)=”myFunction($event)”

With Event binding, a value is passed from a child Component to Parent Component,which can often be a simple html attribute.

<input type="text" (myEvent)="onClick($event)" />

Two-Way binding: [(ngModel)]=”property”

It is an important fourth form that combines property and event binding in a single notation, using the ngModel directive.

<input [(ngModel)]="hero.name">

Directives

An Angular component isn’t more than a directive with the template. When we say that components are the building blocks of Angular applications, we are saying that directives are the building blocks of Angular projects. Let us use built-in Angular directive like ngClass, which is a better example of the existing Angular attribute directive.

<p [ngClass]="{'coffee'=true, 'red'=false}">
Angular 7 Directives Example
</p><style>
.coffee{color: coffee}
.red{color: red}
</style>

Here, based on the [ngClass] directive’s value, the text has color. In our example, the text will be coffee because it is true.

Services

For data or logic that isn’t associated with a specific view, and that you want to share across components, you create a service class. The @Injectable decorator immediately precedes the service class definition. The decorator provides the metadata that allows your service to be injected into client components as a dependency. Angular distinguishes components from services to increase modularity and reusability. By separating a component’s view-related functionality from other kinds of processing, you can make your component classes lean and efficient.

Dependency injection

Dependency injection (DI) lets you keep your component classes lean and efficient. DI does not fetch data from a server, validate the user input, or log directly to the console instead they delegate such tasks to the services. DI is wired into a Angular framework and used everywhere to provide new components with the services or other things they need. Components consume services; that is, you can inject a service into a component, giving the component access to that service class.Bhavika Garg

Software Enginner At SyandanFollowBHAVIKA GARG FOLLOWS

See all (16)

81

3

RelatedBattle of the iOS Architecture Patterns: View Interactor Presenter Entity Router (VIPER)Why hexagonal architecture doesn’t suit me. My DDD implementation is a layered block architectureArchitect a Datastream app( pipe and filters approach)Microservices Part 2: Design PatternsMicroservice is the architecture style most developers adopt when developing modern applications. Although microservices provide many…

Explain the concept of Dependency Injection

Dependency injection is an application design pattern which is implemented by Angular.
It also forms one of the core concepts of Angular.

So what is dependency injection in simple terms?
Let’s break it down, dependencies in angular are nothing but services which have a functionality. Functionality of a service, can be needed by various components and directives in an application. Angular provides a smooth mechanism by which we can inject these dependencies in our components and directives.
So basically, we are just making dependencies which are injectable across all components of an application.

Let’s understand how DI (Dependency Injection) works:

Consider the following service, which can be generated using:

ng g service test

    
      import { Injectable } from '@angular/core';

      @Injectable({
        providedIn: 'root'
      })
      export class TestService {
        importantValue:number = 42;

        constructor() { }

        returnImportantValue(){
          return this.importantValue;
        }
      }
    
  

As one can notice, we can create injectable dependencies by adding the @Injectable decorator to a class.

We inject the above dependency inside the following component:

    
      import { TestService } from './../test.service';
      import { Component, OnInit } from '@angular/core';

      @Component({
        selector: 'app-test',
        templateUrl: './test.component.html',
        styleUrls: ['./test.component.css']
      })
      export class TestComponent implements OnInit {
        value:number;
        constructor(private testService:TestService) { }

        ngOnInit() {
          this.value = this.testService.returnImportantValue();
        }
      }
    
  

One can see we have imported our TestService at the top of the page. Then, we have created an instance inside the constructor of the component and implemented the returnImportantValue function of the service.

From the above example, we can observe how angular provides a smooth way to inject dependencies in any component.