Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Inverse Of Control refers to handing over the power Of object creation. Before that, objects were created with the new keyword whenever we needed them, for example:
public class Main {
private User user;
public String getUserName(a){
returnuser.getName(); }}Copy the code
However, as the number of classes increases and the relationship between classes becomes more and more complex, it becomes difficult to maintain them. The emergence of IOC helps us solve this problem.
In the Spring framework, it maintains a container for storing beans. This container will do some initialization at startup and register beans that need to be used in the project directly with the container. If you want to use beans, you can fetch them directly from the container:
public class Main {
public String getUserName(a) {
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
User user = context.getBean(User.class);
returnuser.getName(); }}Copy the code
You might say isn’t that more complicated? Don’t worry, Spring provides a way to implement IOC. It’s CALLED DI, which stands for dependency injection:
public class Main {
@Autowired
private User user;
public String getUserName(a) {
returnuser.getName(); }}Copy the code
Do you find it very convenient to use now?
So the next question is how do we put an object into Spring’s container?
There are many ways to implement this, using configuration files to place:
<beans>
<bean id="user" class="com.wwj.spring.user"/>
</beans>
Copy the code
Use annotations to put:
@Component
public class User{}Copy the code
Annotations need to be used in conjunction with component scanning:
<component-scan base-package="com.wwj.spring"/>
Copy the code
Use the configuration class to put:
@Configuration
public class MyConfig{
@Bean
public User user{
return new User("zs".20); }}Copy the code
In Spring, the container for managing beans is actually a Map, which is a structure of key-value pairs, the key is the Bean ID, and the value is the object instance of the Bean.
Spring implements inversion of control through dependency injection, freeing programmers’ hands.