Ethickfox kb page with all notes
Spring is an application framework and [inversion of control] container for the Java platform
Framework - Platform that defines application structure
Core part consists of:
There are also other parts, such as:
POJO, who’s lifecycle is driven by container. Можно создать абстрактный бин - как шаблон для других бинов Соответственно есть наследование бинов
Beans Thread safety
Beans are not thread safe, regardless their scopes. To make bean safe, you have to make your object thread safe:
@Lazy - позволяет создавать бин только во время запроса
@ComponentScan - When working with Spring, we can annotate our classes in order to make them into Spring beans. Furthermore, we can tell Spring where to search for these annotated classes, as not all of them must become beans in this particular run.
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.
@Configuration - указывает, что данный класс содержит методы, создающие бины. @Configuration is also a @Component. A class annotated with @Configuration cannot be final because Spring will use CGLIB to create a proxy for @Configuration class.
@Bean without specifying name or alias, the default bean ID will be created based on the name of the method which was annotated with @Bean annotation.@Bean(name={"firstName","name1"}) //ID = firstName, Alias = name1
public SpringBean springBean(){...}
@Component - указывает, что данный класс является бином
Еще раз обратите внимание, что использование этих интерфейсов связывает ваш код с Spring API и не соответствует стилю Inversion of Control. В результате рекомендуется использовать их для компонентов инфраструктуры, которые требуют программного доступа к контейнеру.
Интерфейс, объявляющий методы для чтения бинов из ресурсов или по пути:
Это интерфейс, который позволяет настраивать BeanDefinitions до того, как создаются бины. Он работает на этапе, когда кроме BeanDefinitions еще ничего нету (когда никаких бинов еще нет, ничего нет) и может что-то “подкрутить” в BeanDefinitions. Он содержит единственный метод postProcessorBeanFactory()(который в качестве параметра принимает ConfigurableListableBeanFactory — о ней написано ниже) у которого есть доступ к BeanFactory, т.е. мы можем как-то повлиять на BeanFactory до того, как он начнет работать и повлиять на BeanDefinitions до того, как BeanFactory из них начнет создавать бины.
Интерфейс, который описывает бин, его свойства, аргументы конструктора и другую метаинформацию.
Объявление бина
<bean id="someCat" class="com.ethickeep.entities.Cat"/>
@Qualifier
Qualifies which bean should be injected
@Qualifier("dog")
public Person(@Qualifier("dog") Pet pet)
@Primary
Указание, что использовать данный бин, в случае, если есть несколько кандидатов
@Value
Указание конкретного значения для внедрения
@Value("${person.age}")
private Double age;
@Profile
Maps the bean to that particular profile
// -Dspring.profiles.active=dev
@Component
@Profile("dev")
public class DevDatasourceConfig
@Component
@Profile("!dev")
public class ProdDatasourceConfig
@Order
Implies a specific order, in which the beans will be loaded or prioritized by Spring.
Lower numbers indicate a higher priority. The feature may be used to add beans in a specific order into a collection (ie via @Autowired), among other things. Due to its influence on injection precedence, it may seem like it might influence the singleton startup order also. But in contrast, the dependency relationships and @DependsOn declarations determine the singleton startup order.
@DependsOn
The @DependsOn annotation can force the Spring IoC container to initialize one or more beans before the bean which is annotated by @DependsOn annotation.
The @DependsOn annotation may be used on any class directly or indirectly annotated with @Component or on methods annotated with @Bean.
@Configuration
public class AppConfig {
@Bean("firstBean")
@DependsOn(value = {
"secondBean",
"thirdBean"
})
public FirstBean firstBean() {
return new FirstBean();
}
@Bean("secondBean")
public SecondBean secondBean() {
return new SecondBean();
}
@Bean("thirdBean")
public ThirdBean thirdBean() {
return new ThirdBean();
}
}
@ConfigurationProperties
Externalized configuration and easy access to properties defined in properties files.
@Configuration
@ConfigurationProperties(prefix = "mail")
public class ConfigProperties {
private String hostName;
private int port;
private String from;
// standard getters and setters
}
//mail.hostname=host@mail.com
//mail.port=9000
//mail.from=mailer@mail.com
Спринг позволяет создавать ивенты, которые можно вызывать из контекста
@EventListener - Класс, который следит за ивентом, и в случае его вызова выполняет какой-либо метод.
Он умеет слушать контекст Spring, все “events”, которые с ним происходят. Работает на этапе, когда все уже создано. Также он имеет дженерики <>, в которых мы можем указать что конкретно мы хотим слушать. Обозначается аннотацией @EventListener.
Singleton pattern Singleton Beans - Spring’s approach differs from the strict definition of a singleton since an application can have more than one Spring container. Therefore, multiple objects of the same class can exist in a single application if we have multiple containers. Factory Method Pattern The factory method pattern entails a factory class with an abstract method for creating the desired object.
Application Context - Spring treats a bean container as a factory that produces beans.
External Configuration If we wish to change the implementation of the autowired objects in the application, we can adjust the ApplicationContext implementation we use. For example, we can change the AnnotationConfigApplicationContext to an XML-based configuration class, such as ClassPathXmlApplicationContext
Proxy The proxy pattern is a technique that allows one object — the proxy — to control access to another object — the subject or service. Transactions - In Spring, beans are proxied to control access to the underlying bean. We see this approach when using transactions. This annotation instructs Spring to atomically execute our create method. Without a proxy, Spring wouldn’t be able to control access to our bean and ensure its transactional consistency.
Template Method Pattern In many frameworks, a significant portion of the code is boilerplate code. Templates & Callbacks When executing a query on a database, the same series of steps must be completed:
A callback method is a method that allows the subject to signal to the client that some desired action has completed.