Skip to content

Instantly share code, notes, and snippets.

@aspineon
Forked from jahe/spring-cheatsheet.java
Created August 27, 2021 09:55
Show Gist options
  • Save aspineon/330fed4501d17e43de45ad0319cf32d7 to your computer and use it in GitHub Desktop.
Save aspineon/330fed4501d17e43de45ad0319cf32d7 to your computer and use it in GitHub Desktop.

Revisions

  1. @jahe jahe revised this gist Jun 2, 2017. 1 changed file with 36 additions and 0 deletions.
    36 changes: 36 additions & 0 deletions spring-cheatsheet.java
    Original file line number Diff line number Diff line change
    @@ -138,3 +138,39 @@ public void doOtherStuff() {
    // PlatformTransactionManager - Interface which is implemented by several Transaction Managers
    // (e.g. JmsTransactionManager, JpaTransactionManager)
    // it has commit() and rollback() as methods

    // 3 Steps to achieve transactional behaviour:
    // 1. Set @Transactional on a @Service Bean to achieve that each service method is transactional
    @Service
    @Transactional
    public class MyService {
    @Autowired
    private MyRepository myRepo;
    }

    // 2. In MyConfig declare a transaction manager
    // 3. Annotate MyConfig with @EnableTransactionManagement
    // This tells Spring to generate the transactional Proxies
    // The equivalent in XML configuration is <tx:annotation-driven/>
    @Configuration
    @EnableTransactionManagement
    public class MyConfig {
    @Bean(name = "transactionManager")
    @Profile("test")
    public PlatformTransactionManager transactionManagerForTest() {
    return new DataSourceTransactionManager(dataSourceForTest());
    }

    @Bean(name = "dataSource", destroyMethod = "shutdown")
    @Profile("test")
    public DataSource dataSourceForTest() {
    return new EmbeddedDatabaseBuilder()
    .generateUniqueName(true)
    .setType(EmbeddedDatabaseType.H2)
    .setScriptEncoding("UTF-8")
    .ignoreFailedDrops(true)
    .addScript("schema.sql")
    .addScripts("data.sql")
    .build();
    }
    }
  2. @jahe jahe revised this gist Jun 1, 2017. 1 changed file with 40 additions and 1 deletion.
    41 changes: 40 additions & 1 deletion spring-cheatsheet.java
    Original file line number Diff line number Diff line change
    @@ -98,4 +98,43 @@ public void myStart() {
    public void myEnd() {
    // do something
    }
    }
    }

    // @Transactional - manages a transaction manager
    //
    // Spring doesn't provide any transaction managers itself.
    // It provides hooks to them.
    //
    // Databases have their own transaction managers which will
    // be used by Spring.
    //
    // Spring requests different features of the underlying transaction
    // managers since not all provide the same functionality (e.g. Rollback on Timeout)
    //
    // For @Transactional to work there has to be a Platform Transaction Manager Bean being declared
    // It provides the hook into the underlying transactional system.

    // Apply @Transactional to all methods of a class (can be overridden with @Transactional on a specific method)
    @Transactional
    public class MyBean {
    public void doStuff() {
    }

    public void doOtherStuff() {
    }
    }

    // Properties of the @Transactional Annotation
    // isolation - enum for isolation levels
    // propagation - enum for propagation levels
    // readOnly - boolean to request a readOnly transaction
    // timeout - integer for a timout period
    // value - String for the name of the transaction manager Bean (Default is: "transactionManager")
    // rollbackFor - List of Exception classes which must trigger a rollback
    // rollbackForClassName - List of Strings with classnames of Exception classes which must trigger a rollback
    // noRollbackFor - List of Exception classes which must not trigger a rollback
    // noRollbackForClassName - List of Strings with classnames of Exception classes which must not trigger a rollback

    // PlatformTransactionManager - Interface which is implemented by several Transaction Managers
    // (e.g. JmsTransactionManager, JpaTransactionManager)
    // it has commit() and rollback() as methods
  3. @jahe jahe revised this gist May 31, 2017. No changes.
  4. @jahe jahe revised this gist May 31, 2017. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion spring-cheatsheet.java
    Original file line number Diff line number Diff line change
    @@ -71,7 +71,7 @@ public MyBean myBean() {
    }
    }

    // Call a method right after the constructor + setter methods and a method after the destruction of a bean
    // Call a method right after the constructor + setter methods and a method before the destruction of a bean
    @Bean(initMethod = "myStart", destroyMethod = "myEnd")
    public MyBean myBean() {
    return new MyBean();
  5. @jahe jahe revised this gist May 31, 2017. 1 changed file with 34 additions and 1 deletion.
    35 changes: 34 additions & 1 deletion spring-cheatsheet.java
    Original file line number Diff line number Diff line change
    @@ -34,6 +34,9 @@ public MyBean myBean() {

    bean1 == bean2; // => false

    // In a web app (Spring MVC) there are two more Scopes: "request" and "session"
    // It is also possible to define a custom Scope

    // Calling a @Bean annotated method multiple times
    // result in the exact same instance of the Bean every time it gets called
    // as the scope is "singleton" by default
    @@ -65,4 +68,34 @@ public MyBean myBean() {
    context.add(myBean);
    return myBean;
    }
    }
    }
    }

    // Call a method right after the constructor + setter methods and a method after the destruction of a bean
    @Bean(initMethod = "myStart", destroyMethod = "myEnd")
    public MyBean myBean() {
    return new MyBean();
    }

    public class MyBean {
    public void myStart() {
    // do something
    }

    public void myEnd() {
    // do something
    }
    }

    // OR: on the Bean class directly (JSR 330 -> not hardwired to Spring) - Only works with singleton scoped Beans:
    public class MyBean {
    @PostConstruct
    public void myStart() {
    // do something
    }

    @PreDestroy
    public void myEnd() {
    // do something
    }
    }
  6. @jahe jahe revised this gist May 31, 2017. 1 changed file with 38 additions and 5 deletions.
    43 changes: 38 additions & 5 deletions spring-cheatsheet.java
    Original file line number Diff line number Diff line change
    @@ -2,10 +2,10 @@
    @RequestMapping("/users")
    public @ResponseBody Map<String, String> getUsers () {

    Map<String, String> map = new HashMap<String, String>();
    map.put("user", "Clark Kent");
    Map<String, String> map = new HashMap<String, String>();
    map.put("user", "Clark Kent");

    return map;
    return map;
    }

    // Autowiring multiple Beans of same type into a Java List
    @@ -26,10 +26,43 @@
    @Bean
    @Scope("prototype")
    public MyBean myBean() {
    return new MyBean();
    return new MyBean();
    }

    MyBean bean1 = context.getBean("myBean", MyBean.class);
    MyBean bean2 = context.getBean("myBean", MyBean.class);

    bean1 == bean2; // => false
    bean1 == bean2; // => false

    // Calling a @Bean annotated method multiple times
    // result in the exact same instance of the Bean every time it gets called
    // as the scope is "singleton" by default
    @Configuration
    public class MyConfig {
    @Bean
    public MyBean myBean() {
    return new MyBean();
    }

    public void myTestMethod() {
    MyBean myBean1 = myBean();
    MyBean myBean2 = myBean();

    myBean1 == myBean2 // => true
    }
    }

    // This is achieved by Spring automatically subclassing the MyConfig Class
    // and overriding the myBean() method somehow like this:
    public class SpringMyConfig extends MyConfig {
    @Override
    public MyBean myBean() {
    if (myBean already in context) {
    return myBean;
    }
    else {
    MyBean myBean = super.myBean();
    context.add(myBean);
    return myBean;
    }
    }
  7. @jahe jahe revised this gist May 31, 2017. 1 changed file with 8 additions and 3 deletions.
    11 changes: 8 additions & 3 deletions spring-cheatsheet.java
    Original file line number Diff line number Diff line change
    @@ -16,15 +16,20 @@
    ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    MyBean myFirstBean = context.getBean("myFirstBean", MyBean.class);

    // All Spring managed Beans are Singletons
    // By default all Spring managed Beans are Singletons (@Scope("singleton"))
    MyBean bean1 = context.getBean("myBean", MyBean.class);
    MyBean bean2 = context.getBean("myBean", MyBean.class);

    bean1 == bean2; // => true

    // Create a new Bean on each .getBean(...) call for this type
    // Create a new Bean on each autowiring and each context.getBean() call
    @Bean
    @Scope("prototype")
    public MyBean myBean() {
    return new MyBean();
    }
    }

    MyBean bean1 = context.getBean("myBean", MyBean.class);
    MyBean bean2 = context.getBean("myBean", MyBean.class);

    bean1 == bean2; // => false
  8. @jahe jahe revised this gist May 31, 2017. 1 changed file with 12 additions and 1 deletion.
    13 changes: 12 additions & 1 deletion spring-cheatsheet.java
    Original file line number Diff line number Diff line change
    @@ -14,6 +14,17 @@

    // Get a Bean out of the Spring Application Context
    ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

    MyBean myFirstBean = context.getBean("myFirstBean", MyBean.class);

    // All Spring managed Beans are Singletons
    MyBean bean1 = context.getBean("myBean", MyBean.class);
    MyBean bean2 = context.getBean("myBean", MyBean.class);

    bean1 == bean2; // => true

    // Create a new Bean on each .getBean(...) call for this type
    @Bean
    @Scope("prototype")
    public MyBean myBean() {
    return new MyBean();
    }
  9. @jahe jahe revised this gist May 31, 2017. 1 changed file with 11 additions and 1 deletion.
    12 changes: 11 additions & 1 deletion spring-cheatsheet.java
    Original file line number Diff line number Diff line change
    @@ -6,4 +6,14 @@
    map.put("user", "Clark Kent");

    return map;
    }
    }

    // Autowiring multiple Beans of same type into a Java List
    @Autowired
    private List<MyBean> beans;

    // Get a Bean out of the Spring Application Context
    ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

    MyBean myFirstBean = context.getBean("myFirstBean", MyBean.class);

  10. @jahe jahe revised this gist May 24, 2017. 1 changed file with 0 additions and 10 deletions.
    10 changes: 0 additions & 10 deletions spring-cheatsheet.java
    Original file line number Diff line number Diff line change
    @@ -6,14 +6,4 @@
    map.put("user", "Clark Kent");

    return map;
    }

    // Execute Code on Startup (and refresh) of the application
    @Component
    public class MyListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    // doStuff();
    }
    }
  11. @jahe jahe revised this gist May 24, 2017. 1 changed file with 10 additions and 0 deletions.
    10 changes: 10 additions & 0 deletions spring-cheatsheet.java
    Original file line number Diff line number Diff line change
    @@ -6,4 +6,14 @@
    map.put("user", "Clark Kent");

    return map;
    }

    // Execute Code on Startup (and refresh) of the application
    @Component
    public class MyListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    // doStuff();
    }
    }
  12. @jahe jahe created this gist Feb 26, 2016.
    9 changes: 9 additions & 0 deletions spring-cheatsheet.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,9 @@
    // Return JSON without Jackson mapping classes
    @RequestMapping("/users")
    public @ResponseBody Map<String, String> getUsers () {

    Map<String, String> map = new HashMap<String, String>();
    map.put("user", "Clark Kent");

    return map;
    }