Skip to content

Instantly share code, notes, and snippets.

@xiaoxipang
Last active August 19, 2018 02:27
Show Gist options
  • Select an option

  • Save xiaoxipang/5c1c089840deba15459fbf037d7fa6fe to your computer and use it in GitHub Desktop.

Select an option

Save xiaoxipang/5c1c089840deba15459fbf037d7fa6fe to your computer and use it in GitHub Desktop.
Spring.md

What is Spring framework

Spring is a dependency injection framework.

@Component will tell Spring to take over the instantiate of the class @Autowire will tell Spring to inject and instantiate the class in class

@Component
public class BusinessLogic(){
  // Dependency Injection
  @Autowire
  Logic logic;
}

@Component
public class Logic(){
}

Terms

  • Beans: The different objects that are managed by Spring
  • AutoWiring: The process that Spring identifies the match of the dependencies and populates them
  • Dependency Injection: Inject one obejct as dependency into the another object
  • Inversion Of Control: We are taking the control from the class that needs the dependency and giving the control to the framework
  • IOC Container: Anything that implements IoC
  • Application Context: The place where all of the beans are created and managed

Simple App

  • @SpringBootApplication will scan component in its packages and subpackages for the beans
  • @Primary will guarantee the component will be autowired as first prioirty when there are multiple candidates to select from
  • @Qualifier is another option to decide which canddiate to use when autowiring. Add @Qualifier("whatever") after/before @Component that need to inject and @Autowired that waits for injection. Then that candidate will inject in.

Mandatory injection use constructor injection. Optional injection use setter injection.

Bean Scope

  • Default - singleton

    • singleton - One instance per Spring Context (If there are mutliple Spring Application Context in same JVM, then each of them will have a singleton. This is a little bit different idea comparing with theoritic singleton)
    • prototype - New bean whenever requested
    • request - One bean per HTTP request
    • session - One bean per HTTP session
  • @Scope To change scope, We can use @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) for example.

    If you want to mix use both singleton and prototype for different object, you can use Proxy @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)

  • @ComponentScan can tell application to scan speicified package's components

  • @PostConstruct is used on a method that needs to be executed after dependency injection is done to perform any initialization

  • @PreDestroy is used on methods as a callback notification to signal that the instance is in the process of being removed by the container

CDI Spring
@Inject @Autowired
@Named @Component&@Qualifier
@Singleton one type of scope

IoC Container vs. Application Context vs. Bean Factory

Application Context and Bean Factory are two different implmentation of IoC Container. 99% Spring recommend to use Application Context whenever possible. Application Context = Bean Factory++

Component vs Service vs Repository vs Controller

  • @Component - Generic Component
  • @Repository - encapsulating storage, retrieval, and search behavior typically from a relational database
  • @Service - Business Service Facade
  • @Controller - Controller in MVC pattern

Test

  • @ContextConfiguration is used to determine how to load and configure an {@link org.springframework.context.ApplicationContext ApplicationContext} for integration tests.
  • @RunWith: JUnit will invoke the class it references to run the tests in that class instead of the runner built into JUnit
  • @InjectMocks: Define this object will inject mocks
  • @Mock: Define this object will be mocked

Spring Framework vs. Spring

  • Spring Framework: DI and testibility, Plumping code, Integration with other framework
  • Spring MVC: Help develop web application/Restful API
  • Spring Boot: Auto Configuration, , monitoring, logging, embedded server

AOP

Intecept any method calls to beans and do somthings around that. Jweaver can even intercept change of values on a field.

  • CommandLineRunner: As soon as application launches, this will trigger and you can do anything in there

  • @Before: make a intercept to be called before each method

  • pointcut: The expression used to defines what kind of method I would want to intercept, i.e "execution(* PACKAGE.*.*(..))"

  • Advice: The logic inside the interceptor

  • JoinPoint: Specific interception of a method call

  • Aspect = pointcut + Advice

  • Weaved: This whole interception process around your code is called weaving, the framework called weaver

  • @After Any thing after a method will be intercept

    @Aspect
    @Configuration
    public class AfterAopAspect {
    
        private static Logger logger = LoggerFactory.getLogger(this.getClass());
    
        @AfterReturning(
                value = "execution(* com.zingoer.spring.aop.springaop.business.*.*(..))",
                returning = "result"
        )
        public void after(JoinPoint joinPoint, Object result){
    
            logger.info(" {} returned with value {}", joinPoint, result);
        }
    
        @AfterThrowing(
                value = "execution(* com.zingoer.spring.aop.springaop.business.*.*(..))",
                throwing = "exception"
        )
        public void afterThrowing(JoinPoint joinPoint, Exception exception){
    
            logger.info(" {} returned with value {}", joinPoint, exception);
        }
    
        @After(
                value = "execution(* com.zingoer.spring.aop.springaop.business.*.*(..))"
        )
        public void afterThrowing(JoinPoint joinPoint){
    
            logger.info(" after execution of {}", joinPoint);
        }
    }
  • @Around Can be use with ProceedingJoinPoint to do something around method interceptor

Best practice: Put all Pointcut into one config class for easy management. Then other aspect can use these pointcut in their advices

Spring Data Repository

  • JpaRepository<Entity, IdType> helps you impelment all default database queries
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment