它将程序中创建对象的控制权交给Spring 框架来管理,以便降低计算机代码之间的辑合度
package com.example.demo.entity;
import lombok.Data;
import java.io.Serializable;
@Data
public class User implements Serializable {
private int id;
private String name;
}
package com.example.demo.config;
import com.example.demo.entity.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class UserConfig {
//将此返回的值生成一个bean
@Bean("user01")
public User user() {
User user = new User();
user.setId(1);
user.setName("Tom");
return user;
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class IocTest {
@Autowired
private ApplicationContext applicationContext;
@Test
public void testIoc() {
User user = (User) applicationContext.getBean("user01");
System.out.println(user);
}
}
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>