Spring learning (two)
Chapter 2 Spring's constructor injection, Singleton (singleton mode), automatic assembly and life cycle
Article Directory
One, constructor injection
Take the user class as an example. For the id, name, and password attributes, the following methods of constructor injection can be performed in the configuration file:
<constructor-arg index="0" value=" "/>
<constructor-arg index="1" value=" "/>
<constructor-arg index="2" value=" "/>
<constructor-arg type="int" value=" "/>
<constructor-arg type="java.lang.String" value=" "/>
<constructor-arg type="java.lang.String" value=" "/>
<constructor-arg name="id" value=" "/>
<constructor-arg name="name" value=" "/>
<constructor-arg name="password" value=" "/>
Two, Singleton (singleton mode)
When the scope of a bean is Singleton, there will only be one shared bean instance in the Spring IoC container, and all requests to the bean, as long as the id matches the bean definition, will only return the same instance of the bean. Singleton is a singleton type, that is, when the container is created, a bean object is automatically created at the same time. It does not matter whether you use it or not, it exists, and the object obtained every time is the same object. Note that the Singleton scope is the default scope in Spring. To define a bean as a singleton in XML, you can configure it like this:
<bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">
Three, automatic assembly
Auto-wiring is a way to use spring to satisfy bean dependencies. Spring will look for dependent beans for a bean in the application context.
default-autowire=" "
- byName (automatic assembly by name)
In the process of manually configuring xml, errors such as missing letters and capitalization often occur, and cannot be checked, which reduces development efficiency.
The use of automatic assembly will avoid these errors and simplify the configuration.
- byType (automatic assembly by type)
First of all, you need to ensure: objects of the same type are unique in the spring container. If it is not unique, a non-unique exception will be reported.
Fourth, the life cycle
default-init-method="defaultInit" default-destroy-method="defaultDestroy
init-method="start" destroy-method="stop"
public class LifeCycle implements InitializingBean, DisposableBean {
public void start() {
System.out.println("LifeCycle start");
}
public void stop() {
System.out.println("LifeCycle stop");
}
public void defaultInit() {
System.out.println("defaultInit");
}
public void defaultDestroy() {
System.out.println("defaultDestroy");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet");
}
@Override
public void destroy() throws Exception {
System.out.println("destroy");
}
}
to sum up
The above is what I will talk about today.