一、概述

我们知道,在使用Spring框架后,Bean统一都交给IOC容器去管理和创建,那么将一个对象加入到Spring容器中有哪些方式呢,今天我们结合具体的代码来总结一下。

二、第一种方式: XML配置方式

XML配置的方式,是Spring最早支持的方式,不过现在XML方式已经用的比较少了,基本上都是用后面的配置方式替代了。

public class Student {
}
 
<beans xmlns="<http://www.springframework.org/schema/beans>"
	   xmlns:xsi="<http://www.w3.org/2001/XMLSchema-instance>"
	   xsi:schemaLocation="<http://www.springframework.org/schema/beans> <http://www.springframework.org/schema/beans/spring-beans.xsd>">
	<bean id="student" class="com.wsh.injectbean.method_01.Student"/>
</beans>
 
/**
 * 第一种方式: XML文件配置
 */
public class Client {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring-config.xml");
		System.out.println(applicationContext.getBean("student"));
	}
}

三、第二种方式: 使用@Component注解 + @ComponentScan包扫描方式

为了解决bean太多时,XML文件过大,从而导致膨胀不好维护的问题。在Spring2.5中开始支持:@Component、@Repository、@Service、@Controller等注解定义bean。@Component放在类名上面,然后通过@ComponentScan指定一个路径,Spring进行扫描带有@Componet注解的bean,然后加至容器中。

注意,这种方式不单单指的是@Component注解,还包括@Controler、@Service、@Repository等派生的注解。

具体代码如下:

@Component
public class UserHandler {
}
 
@Service
public class UserService {
}
 
@Repository
public class UserDao {
}
 
@Controller
public class UserController {
}
 
@ComponentScan("com.wsh.injectbean.method_02")
@Configuration
public class AppConfig {
}
 
/**
 * 第二种方式: 使用@Component注解 + @ComponentScan包扫描方式
 * 包括@Controler、@Service、@Repository等派生的注解。
 * 为了解决bean太多时,xml文件过大,从而导致膨胀不好维护的问题。在spring2.5中开始支持:@Component、@Repository、@Service、@Controller等注解定义bean。
 * 其实本质上@Controler、@Service、@Repository也是使用@Component注解修饰的。
 * <p>
 * 通常情况下:
 *
 * @Controller:一般用在控制层
 * @Service:一般用在业务层
 * @Repository:一般用在持久层
 * @Component:一般用在公共组件上
 */
public class Client {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
		System.out.println(applicationContext.getBean("userDao"));
		System.out.println(applicationContext.getBean("userService"));
		System.out.println(applicationContext.getBean("userController"));
		System.out.println(applicationContext.getBean("userHandler"));
	}
}

四、第三种方式:@Configuration + @Bean方式

这种方式其实也是我们最常用的方式之一,@Configuration用来声明一个配置类,然后使用 @Bean 注解声明一个bean,将其加入到Spring容器中。通常情况下,如果项目中有使用到第三方类库中的工具类的话,我们都是采用这种方式注册Bean。