1、@Component注解
- 在相关类上加上@Component注解即可
- 类名的小驼峰形式即为bean的id值
- 该方式创建bean优先级最低
package com.yusian.entity;
import org.springframework.stereotype.Component;
@Component
public class User {
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
'}';
}
}
2、@Bean注解
- 以使用注解的方式创建Spring工厂为例,在Spring配置类中添加一个方法返回相关对象,方法上加@Bean注解
- 方法名即为bean对象的id值
- 该方式的优化级大于@Component,但低于xml配置文件
package com.yusian.config;
import com.yusian.entity.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ComponentScan("com.yusian.entity")
@ImportResource("applicationContext.xml")
public class AppConfig {
@Bean
public User user() {
User user = new User();
user.setId(2);
return user;
}
}
3、xml配置文件
- 配置文件的方式创建Bean最为简单,添加
<bean>
标签即可
- 该方式优先级最高,可覆盖前两者
<?xml version="1.0" encoding="UTF-8"?>
<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="user" class="com.yusian.entity.User">
<property name="id" value="3"/>
</bean>
</beans>