What is Spring?
The purpose of the Spring framework is to decouple the main business logic in different ways according to different code, through IOC to decouple the main business logic and through AOP to decouple the system-level services (such as logging, security, transaction, etc.) to decouple the main business logic. A Web layer framework, Spring MVC, is also provided.
The core components of Spring
IOC Spring core module
DAO Spring’s support for accessing databases, primarily JDBC
Spring support for the MVC design Pattern (SSM)
AOP (Aspect Orientied Programing) is section-oriented programming
ORM object relational mapping Spring and ORM framework integrate Mybatis
The Spring container
Before introducing the Spring container, let’s first introduce beans. Simply put, objects managed by the Spring container are called beans, such as Controller/Action, Service, and Dao.
<bean id="userControllerId" class="org.a.IOC.UserController"></bean>
<bean id="userServiceId" class="org.a.IOC.UserServiceImpl"></bean>
<bean id="BookDaoId" class="org.a.IOC.UserDaoImpl"></bean>
Copy the code
The Spring container manages the instantiation and assembly of all bean objects in the project. There are two types, BeanFactory and ApplicationContext. ApplicationContext is a subinterface of the BeanFactory that provides the following functionality:
- Easier integration with Spring’s AOP features
- Message resource processing (for internationalization)
- Event publishing
- Application-layer specific contexts, such as WebApplicationContext used in Web applications
The above features are just a few things to know, but for the difference between the two, we need to keep in mind:
- The BeanFactory uses a lazy-loading strategy, reading the configuration information to generate an instance of a bean on the first call to getBean().
- The ApplicationContext reads the configuration information at initialization, generating instances of all beans. The result of these two features is that -BeanFactory throws an exception when it calls getBean() if the configuration information is wrong, while ApplicationContext throws an exception when it initializes, helping us to check that the configuration is correct in time.
- Both support BeanPostProcessor and spring BeanFactoryPostProcessor, but the BeanFactory need to manually register, and ApplicationContext is automatically registered.
Most of the time we use ApplicationContext, and the rest of this blog is based on ApplicationContext.
Configuring metadata
The Spring container reads metadata to get objects to instantiate and assemble. Metadata comes in three formats: XML files, Java annotations, and Java code. This article covers only metadata in XML format and Java annotation format.
<beans>
<bean id="BookServiceId" class="org.tyshawn.service.impl.BookServiceImpl">
<property name="bookDao" ref="BookDaoId"></property>
</bean>
<bean id="BookDaoId" class="org.tyshawn.dao.Impl.BookDaoImpl"></bean>
</beans>
Copy the code
The above code is metadata based on XML files, Two implementation class ApplicationContext ClassPathXmlApplicationContext and FileSystemXmlApplicationContext metadata used to load the XML format. The difference between the two lies in the ClassPathXmlApplicationContext is based on the class path, and FileSystemXmlApplicationContext is based on the path to the file.
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/bean.xml");
ApplicationContext context = new FileSystemXmlApplicationContext("D:\\springtest\\src\\main\\resources\\spring\\bean.xml");
Copy the code
ApplicationContext implementation class AnnotationConfigApplicationContext loads the Java metadata annotation format.
@Configuration
@ComponentScan(basePackages = "org.tyshawn")
public class AppConfig {
}
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Copy the code
IOC
IoC is also known as dependency injection (DI). This is the process in which bean dependencies are first defined through properties set on object instances, and then injected by the Spring container when the bean is created (this injection process is also called assembly). There are two types of dependency injection, constructor – based injection and Setter – based injection.
Construction-based injection
public interface IBookDao {
void insert();
}
public class BookDaoImpl implements IBookDao {
@Override
public void insert() {
System.out.println("add book");
}
}
public interface IBookService {
void addBook();
}
public class BookServiceImpl implements IBookService {
private IBookDao bookDao;
public BookServiceImpl(IBookDao bookDao) {
this.bookDao = bookDao;
}
@Override
public void addBook() {
this.bookDao.insert();
}
}
<beans>
<bean id="BookServiceId" class="org.tyshawn.service.impl.BookServiceImpl">
<constructor-arg ref="BookDaoId"/>
</bean>
<bean id="BookDaoId" class="org.tyshawn.dao.Impl.BookDaoImpl"></bean>
</beans>
public class Test{
public static void main(String[] args) throws ParseException {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/bean.xml");
IBookService bookService = (IBookService) context.getBean("BookServiceId"); bookService.addBook(); }}Copy the code
Setter-based injection
public interface IBookDao {
void insert();
}
public class BookDaoImpl implements IBookDao {
@Override
public void insert() {
System.out.println("add book");
}
}
public interface IBookService {
void addBook();
}
public class BookServiceImpl implements IBookService {
private IBookDao bookDao;
public void setBookDao(IBookDao bookDao) {
this.bookDao = bookDao;
}
@Override
public void addBook() {
this.bookDao.insert();
}
}
<beans>
<bean id="BookServiceId" class="org.tyshawn.service.impl.BookServiceImpl">
<property name="bookDao" ref="BookDaoId"></property>
</bean>
<bean id="BookDaoId" class="org.tyshawn.dao.Impl.BookDaoImpl"></bean>
</beans>
public class Test{
public static void main(String[] args) throws ParseException {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/bean.xml");
IBookService bookService = (IBookService) context.getBean("BookServiceId"); bookService.addBook(); }}Copy the code
The scope of the Bean
There are six scopes for beans, the last four of which only support Web applications.
scope | describe |
---|---|
singleton | By default, beans have only one instance per Spring container |
prototype | Each bean retrieved from the Spring container is a new instance |
request | Beans have only one instance per HTTP Request and only support Web applications |
session | Beans have only one instance per HTTP Session and only support Web applications |
application | The bean has only one instance per ServletContext and only supports Web applications |
websocket | Beans have only one instance per WebSocket and only support Web applications |
<bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
<bean id="loginAction" class="com.something.LoginAction" scope="request"/>
<bean id="userPreferences" class="com.something.UserPreferences" scope="session"/>
<bean id="appPreferences" class="com.something.AppPreferences" scope="application"/>
Copy the code
The difference between singleton and Application is that (1) a bean has only one instance in each Spring container, whereas an application can have multiple containers. (2) A bean has only one instance in each Spring container. There is only one instance of a bean in the entire application.
// As you can see, Public class Test{public static void main(String[] args) throws ParseException {ApplicationContext context1 = new ClassPathXmlApplicationContext("classpath:spring/bean.xml");
ApplicationContext context2 = new FileSystemXmlApplicationContext("D:\\springtest\\src\\main\\resources\\spring\\bean.xml");
IBookService bookService1 = (IBookService) context1.getBean("BookServiceId");
IBookService bookService2 = (IBookService) context2.getBean("BookServiceId");
System.out.println(bookService1);
System.out.println(bookService2);
}
}
org.tyshawn.service.impl.BookServiceImpl@23faf8f2
org.tyshawn.service.impl.BookServiceImpl@2d6eabae
Copy the code
A singleton bean with multi-instance bean dependencies
A bean is scoped to singleton and its properties are scoped to Prototype, as shown below:
<bean id="BookServiceId" class="org.tyshawn.service.impl.BookServiceImpl" scope="singleton">
<constructor-arg ref="BookDaoId"/>
</bean>
<bean id="BookDaoId" class="org.tyshawn.dao.Impl.BookDaoImpl" scope="prototype"></bean>
Copy the code
We want the same bean every time we get the BookServiceId, and its property, BookDaoId, is a new bean. This is not possible because BookServiceId is only instantiated and loaded once. To achieve the desired effect, we need to use method injection:
Methods to inject
The Spring framework implements this method injection by using bytecode generators from the CGLIB library to dynamically generate subclasses that override the method.
public class BookServiceImpl implements IBookService {
private IBookDao bookDao;
public IBookDao getBookDao() {
return bookDao;
}
@Override
public void addBook() {
IBookDao bookDao = getBookDao();
System.out.println(bookDao);
}
}
<bean id="BookServiceId" class="org.tyshawn.service.impl.BookServiceImpl" scope="singleton">
<lookup-method name="getBookDao" bean="BookDaoId"></lookup-method>
</bean>
<bean id="BookDaoId" class="org.tyshawn.dao.Impl.BookDaoImpl" scope="prototype"></bean>
public class Test{
public static void main(String[] args) throws ParseException {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/bean.xml");
BookServiceImpl bookService1 = (BookServiceImpl) context.getBean("BookServiceId");
BookServiceImpl bookService2 = (BookServiceImpl) context.getBean("BookServiceId");
bookService1.addBook();
bookService2.addBook();
}
}
org.tyshawn.dao.Impl.BookDaoImpl@6121c9d6
org.tyshawn.dao.Impl.BookDaoImpl@87f383f
Copy the code
The life cycle of the Bean
Lifecycle callback
(1) Initialize the callback
After the bean is instantiated in the Spring container and the property values are set, the initialization callback is performed. The initial callback can be set in two ways:
Method 1 (Recommended)
<bean id="exampleInitBean1" class="org.tyshawn.example.ExampleBean" init-method="init"/>
public class ExampleBean {
public void init() {
System.out.println("do some initialization work."); }}Copy the code
Method 2 (not recommended)
<bean id="exampleInitBean2" class="org.tyshawn.example.AnotherExampleBean"/>
public class AnotherExampleBean implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("do some initialization work.");
}
}
public class Test{
public static void main(String[] args) throws ParseException {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/bean.xml");
ExampleBean example1 = (ExampleBean) context.getBean("exampleInitBean1");
AnotherExampleBean example2 = (AnotherExampleBean) context.getBean("exampleInitBean2"); System.out.println(example1); System.out.println(example2); }}do some initialization work.
do some initialization work.
org.tyshawn.example.ExampleBean@4eb7f003
org.tyshawn.example.AnotherExampleBean@eafc191
Copy the code
(2) Destroy callback
Before the bean is destroyed, a destruction callback is executed. The destruction callback can be set in two ways:
Method 1 (Recommended)
<bean id="exampleDestoryBean1" class="org.tyshawn.example.ExampleBean" destroy-method="destory"/>
public class ExampleBean {
public void destroy() {
System.out.println("do some destruction work."); }}Copy the code
Method 2 (not recommended)
<bean id="exampleDestoryBean2" class="org.tyshawn.example.AnotherExampleBean"/>
public class AnotherExampleBean implements DisposableBean {
@Override
public void destroy() {
System.out.println("do some destruction work.");
}
}
public class Test{
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/bean.xml");
ExampleBean example1 = (ExampleBean) context.getBean("exampleDestoryBean1");
AnotherExampleBean example2 = (AnotherExampleBean) context.getBean("exampleDestoryBean2"); / / when the container is closed, the bean container was destroyed context. RegisterShutdownHook (); }}do some destruction work.
do some destruction work.
Copy the code
(3) Both methods of initializing callback/destroying callback are configured simultaneously
What happens when both methods of initiating/destroying callbacks are configured together?
<bean id="exampleDestoryBean2" class="org.tyshawn.example.AnotherExampleBean" destroy-method="cleanup"/>
public class AnotherExampleBean implements DisposableBean {
@Override
public void destroy() {
System.out.println("do some destruction work.");
}
public void cleanup() {
System.out.println("do some cleanup work.");
}
}
public class Test{
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/bean.xml");
AnotherExampleBean example2 = (AnotherExampleBean) context.getBean("exampleDestoryBean2"); context.registerShutdownHook(); }}do some destruction work.
do some cleanup work.
Copy the code
The result is to execute both methods, but DisposableBean/InitializingBean first, destroy-method/init-method second.
(4) Start and close callbacks
If beans in the Spring container implement the Lifecycle interface, the start() method of those beans will be called when the Spring container is started and the stop() method of those beans will be called when the Spring container is closed.
public interface Lifecycle {
void start();
void stop();
boolean isRunning();
Copy the code
In many cases, the order in which the start() and stop() methods are called is important. If there is a dependency between the two beans, for example, if A depends on B (which is an attribute of A), then A calls start() first and B calls stop() first. But if we don’t know the dependencies and want A to call the start() method before B, then we can replace Lifecycle with a SmartLifecycle interface.
public interface Phased {
int getPhase();
}
public interface SmartLifecycle extends Lifecycle, Phased {
boolean isAutoStartup();
void stop(Runnable callback);
Copy the code
Methods of the SmartLifecycle interface are as follows:
When isAutoStartup() returns true, the Start () method of the bean is called when the Spring container is started
When isRunning() returns true, the Spring container will call the bean’s Stop (Runnable Runnable) method when it is destroyed
GetPhase () returns the priority, and when there are more than one bean, the start() method with a large value is executed first, and the order of destruction is reversed. The container does not implement the SmartLifecycle interface and a bean that implements the Lifecycle interface returns a value of 0. A negative number represents the highest priority.
<bean id="exampleDestoryBean" class="org.tyshawn.example.ExampleBean" />
public class ExampleBean implements SmartLifecycle {
private boolean isRunning = false;
@Override
public boolean isAutoStartup() {
return true;
}
@Override
public void stop(Runnable runnable) {
runnable.run();
System.out.println("stop runnable ...");
}
@Override
public void start() {
isRunning = true;
System.out.println("start run ...");
}
@Override
public void stop() {
System.out.println("stop run ...");
}
@Override
public boolean isRunning() {
return isRunning;
}
@Override
public int getPhase() {
return- 1; } } public class Test{ public static void main(String[] args) throws Exception { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/bean.xml");
ExampleBean example = (ExampleBean) context.getBean("exampleDestoryBean");
System.out.println(example);
context.registerShutdownHook();
}
}
start run ...
org.tyshawn.example.ExampleBean@1b26f7b2
stop runnable ...
Copy the code
(5) Initialize/destroy callback and start/close callback execution sequence
Now that we know about initialization/destruction and start/close callbacks, we must wonder what their execution looks like when they both exist, as follows:
<bean id="exampleBean" class="org.tyshawn.example.ExampleBean" init-method="init" destroy-method="destroy"/>
public class ExampleBean implements SmartLifecycle{
private boolean isRunning = false;
public void init() {
System.out.println("do some init work.");
}
public void destroy() {
System.out.println("do some destruction work.");
}
@Override
public boolean isAutoStartup() {
return true;
}
@Override
public void stop(Runnable runnable) {
runnable.run();
System.out.println("stop runnable ...");
}
@Override
public void start() {
isRunning = true;
System.out.println("start run ...");
}
@Override
public void stop() {
System.out.println("stop run ...");
}
@Override
public boolean isRunning() {
return isRunning;
}
@Override
public int getPhase() {
return- 1; } } public class Test{ public static void main(String[] args) throws Exception { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/bean.xml");
ExampleBean example1 = (ExampleBean) context.getBean("exampleBean"); context.registerShutdownHook(); }}do some init work.
start run ...
stop runnable ...
do some destruction work.
Copy the code
As you can see from the above example, the container starts with an initialization callback and then a startup callback. When the container is closed, the close callback is performed, followed by the destruction callback.
XXXAware
Spring provides a set of interfaces that end with Aware, translated as XXXAware, to implement the corresponding XXXAware interface if a bean needs Spring to provide certain dependencies. Here are the three Aware interfaces we use:
interface | role |
---|---|
BeanNameAware | Provides the ID of the bean when it is declared |
BeanFactoryAware | Provide the BeanFactory container |
ApplicationContextAware | Provide the ApplicationContext container |
(1) BeanNameAware
<bean id="exampleDestoryBean" class="org.tyshawn.example.ExampleBean" />
public class ExampleBean implements BeanNameAware{
@Override
public void setBeanName(String beanName) {
System.out.println("beanName: " + beanName);
}
}
public class Test{
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/bean.xml");
ExampleBean example = (ExampleBean) context.getBean("exampleDestoryBean");
}
}
beanName: exampleDestoryBean
Copy the code
(2) BeanFactoryAware
<bean id="exampleBean" class="org.tyshawn.example.ExampleBean" />
public class AnotherExampleBean implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("ApplicationContext: " + applicationContext);
}
}
public class Test{
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/bean.xml");
ExampleBean example = (ExampleBean) context.getBean("exampleBean");
}
}
BeanFactory: org.springframework.beans.factory.support.DefaultListableBeanFactory@2344fc66: defining beans [exampleBean]; root of factory hierarchy
Copy the code
(3) ApplicationContextAware
<bean id="exampleBean" class="org.tyshawn.example.AnotherExampleBean" />
public class AnotherExampleBean implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("ApplicationContext: " + applicationContext);
}
}
public class Test{
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/bean.xml");
AnotherExampleBean example = (AnotherExampleBean) context.getBean("exampleBean");
}
}
ApplicationContext: org.springframework.context.support.ClassPathXmlApplicationContext@573fd745: startup date [Thu Apr 18 18:59:43 CST 2019]; root of context hierarchy
Copy the code
BeanPostProcessor
If we want to add some custom logic before and after the Spring container completes the bean’s initialization, we can register one or more custom BeanPostProcessor implementations with the container. When we have multiple BeanPostProcessor customizations, we also implement the Ordered interface.
<bean id="exampleBean" class="org.tyshawn.example.AnotherExampleBean" init-method="init"/>
<bean class="org.tyshawn.example.CustomBeanPostProcessor1"/>
<bean class="org.tyshawn.example.CustomBeanPostProcessor2"/>
public class CustomBeanPostProcessor1 implements BeanPostProcessor, Ordered {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Bean custom logic before init() method 1.");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Bean custom logic after executing init() method 1.");
return bean;
}
@Override
public int getOrder() {
return 2;
}
}
public class CustomBeanPostProcessor2 implements BeanPostProcessor, Ordered {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Bean custom logic before init() method 2.");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Custom logic for bean after init() method 2.");
return bean;
}
@Override
public int getOrder() {
return 1;
}
}
public class AnotherExampleBean {
public void init() {
System.out.println("init() ...");
}
}
public class Test{
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/bean.xml");
AnotherExampleBean example = (AnotherExampleBean) context.getBean("exampleBean"); }} Bean custom logic before init() method 2. Bean custom logic before init() method 1. Init ()... Bean custom logic after init() method 2. Bean custom logic after init() method 1.Copy the code
The life cycle of the bean
What is the life cycle of beans in the Spring container? (1) Instantiate (2) Set the property value (3) Call the setBeanName() method of BeanNameAware (4) Call the setBeanFactory() method of BeanameAware (5) Invoke the ApplicationContext setApplicationContext () method (6) to invoke the BeanPostProcessor postProcessBeforeInitialization () method (7) Invoke the InitializingBean afterPropertiesSet () method (8) to invoke the XML configuration initialization method (9) calls the BeanPostProcessor postProcessAfterInitialization () method (10) The container is started. (11) The bean is ready to use. (12) The container is closed. (13) Call to DisposableBean’s deStory () method. (14) Call to the XML configured destruction method
Example code is as follows:
<bean id="exampleBean" class="org.tyshawn.example.ExampleBean" init-method="init" destroy-method="dest"/>
<bean class="org.tyshawn.example.CustomBeanPostProcessor"/>
public class CustomBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Call the BeanPostProcessor postProcessBeforeInitialization () method." ");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Call the BeanPostProcessor postProcessAfterInitialization () method." ");
return bean;
}
}
public class ExampleBean implements InitializingBean, DisposableBean, SmartLifecycle, BeanNameAware, BeanFactoryAware, ApplicationContextAware {
private boolean isRunning = false;
public void init() {
System.out.println("Call the initialization method of the XML configuration");
}
public void dest() {
System.out.println("Invoke xmL-configured destruction methods");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Call the afterPropertiesSet() method of the InitializingBean");
}
@Override
public void destroy() {
System.out.println("Call The Destory () method to DisposableBean");
}
@Override
public boolean isAutoStartup() {
return true;
}
@Override
public void stop(Runnable runnable) {
runnable.run();
System.out.println("Container closed.");
}
@Override
public void start() {
isRunning = true;
System.out.println("Container started.");
}
@Override
public void stop() {
}
@Override
public boolean isRunning() {
return isRunning;
}
@Override
public int getPhase() {
return- 1; } @Override public voidsetBeanName(String beanName) {
System.out.println(Call the setBeanName() method of BeanNameAware);
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println("Call the setBeanFactory() method of BeanFactoryAware");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("Call the setApplicationContext() method of ApplicationContext");
}
public void sayHello() {
System.out.println("Bean is ready to use.");
}
}
public class Test{
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/bean.xml");
ExampleBean example = (ExampleBean) context.getBean("exampleBean"); example.sayHello(); context.registerShutdownHook(); }} call BeanNameAwaresetThe BeanName() method calls BeanFactoryAwaresetThe BeanFactory() method calls ApplicationContext'ssetApplicationContext () method call BeanPostProcessor postProcessBeforeInitialization () method calls the InitializingBean afterPropertiesSet () method To invoke the XML configuration initialization method calls the BeanPostProcessor postProcessAfterInitialization container startup () method. The bean to use. The container closes. Call DisposableBean's destory() method to invoke the DESTRUCTION method of the XML configurationCopy the code
FactoryBean
BeanFactory is a Spring container in which all instances of beans in your application are stored. What is a FactoryBean?
FactoryBean is a factory that generates beans. Normally we configure beans using XML files, but if we have complex initialization logic that can be expressed better in Java code than verbose XML, we can create our own FactoryBeans and write complex initialization logic in that class. The custom FactoryBean is then inserted into the container.
public interface FactoryBean<T> { T getObject() throws Exception; Class<? > getObjectType(); boolean isSingleton();Copy the code
FactoryBean interface
- GetObject (), which returns an instance of the object created by the factory.
- GetObjectType (), which returns the object type.
- IsSingleton, whether it is a singleton.
<bean id="tool" class="org.tyshawn.example.ToolFactory">
<property name="toolName" value="iphone xs"/>
</bean>
public class Tool {
private String name;
public Tool(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class ToolFactory implements FactoryBean<Tool> {
private String toolName;
@Override
public Tool getObject() throws Exception {
returnnew Tool(toolName); } @Override public Class<? >getObjectType() {
return Tool.class;
}
@Override
public boolean isSingleton() {
return false;
}
public String getToolName() {
return toolName;
}
public void setToolName(String toolName) {
this.toolName = toolName;
}
}
public class Test{
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/bean.xml");
Tool tool = (Tool) context.getBean("tool");
System.out.println(tool.getName());
}
}
iphone xs
Copy the code
Annotation-based container configuration
(1) Container configuration
@ComponentScan is used to configure the class scanning path.
@Configuration
@ComponentScan(basePackages = "org.example")
public class AppConfig {
}
Copy the code
Equivalent to XML configuration
<? xml version="1.0" encoding="UTF-8"? > <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.example"/>
</beans>
Copy the code
(2) the bean declaration
In an XML-based configuration, the following line declares a bean.
<bean id="bookDaoId" class="org.tyshawn.dao.Impl.BookDaoImpl"></bean>
Copy the code
In an annotation-based container configuration, we can declare a bean with the following annotations.
- Component declares a bean.
- Controller, declare a Web layer bean.
- Declare a Service layer bean.
- @repository, declare a DAO layer bean. (3) Automatically inject properties
If there are multiple injected attributes, specify the name through @qualifier. @resource = @autowired + @qualifier
@Configuration
@ComponentScan(basePackages = "org.tyshawn")
public class AppConfig {
}
@Repository("bookDao")
public class BookDaoImpl implements IBookDao {
@Override
public void insert() {
System.out.println("add book");
}
}
@Service("bookService")
public class BookServiceImpl implements IBookService {
// @Autowired
// @Qualifier(value = "bookDao")
@Resource(name = "bookDao")
private IBookDao bookDao;
@Override
public void addBook() {
bookDao.insert();
}
}
public class Test{
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
IBookService bookService = context.getBean("bookService", BookServiceImpl.class);
bookService.addBook();
}
}
add book
Copy the code
(3) the scope
- @ the Scope (” singleton “)
- @ the Scope (the “prototype”)
- @RequestScope
- @SessionScope
- @ApplicationScope
@Configuration
@ComponentScan(basePackages = "org.tyshawn")
public class AppConfig {
}
@Component("exampleBean")
@Scope("prototype")
public class ExampleBean {
}
public class Test{
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
ExampleBean exampleBean1 = context.getBean("exampleBean", ExampleBean.class);
ExampleBean exampleBean2 = context.getBean("exampleBean", ExampleBean.class);
System.out.println(exampleBean1);
System.out.println(exampleBean2);
}
}
org.tyshawn.example.ExampleBean@64c87930
org.tyshawn.example.ExampleBean@400cff1a
Copy the code
(4) Lifecycle callback
- @postconstruct, initialize the callback
- @predestroy, destroy callback
@Configuration
@ComponentScan(basePackages = "org.tyshawn")
public class AppConfig {
}
@Component("exampleBean")
public class ExampleBean {
@PostConstruct
public void init() {
System.out.println("Initialization method");
}
@PreDestroy
public void destroy() {
System.out.println("Method of Destruction");
}
}
public class Test{
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
ExampleBean exampleBean = context.getBean("exampleBean", ExampleBean.class); System.out.println(exampleBean); context.registerShutdownHook(); }} initialization method org. Tyshawn. Example. ExampleBean @ 5 d47c63f destroy methodCopy the code
This concludes our introduction to Spring, which should be enough for beginners to understand what Spring is and to impress the interviewer. If you want to learn more about Spring, go to the official documentation and read the source code.
Source: t.i m/KZFP
Open Source Project Recommendation
The authors recommend open source projects:
- Pre Is a RBAC permission management system based on Spring Boot, Spring Security, and Vue
- Prex based on Spring Cloud, Oauth2, Vue of the front and back end separation of the microservice architecture RBAC permission management system
Concern public number reply open source project can be obtained