Spring原始注解:主要是替代的配置
@Component----------使用在类上用于实例化Bean(通用)
@Component(“UserServiceBean”)
<bean id="UserServiceBean" class="com.service.impl.UserServiceImpl"></bean>
@Controller------------使用在web层类用于实例化Bean
@Cotrollert(“UserControllerBean”)
<bean id="UserControllerBean" class="com.web.impl.UserControllerImpl"></bean>
@Service---------------使用在service层类用于实例化Bean
@Service(“UserControllerBean”)
<bean id="UserServiceBean" class="com.Service.impl.UseServiceImpl"></bean>
@Repository-----------使用在dao层类用于实例化Bean
@Repository(“UserDaoBean”)
@Autowired------------使用在字段上用于根据类型依赖注入(不建议使用)
@Qualifier--------------结合@Autowired一起使用,用于根据名称(id)进行依赖注入
@Autowired
@Qualifier(“UserDaoBean”)//按照id从容器中进行匹配
@Resource------------相当于@Autowired+@Qualifier,按照名称(id)进行注入(name=“id”)(推荐使用)
@Resource(name=“UserDaoBean”) //Resource也是通过id匹配
@Value------------------注入普通属性(和jstl结合)
@Value(“GuoDeGang”)
private String name;
@Scope----------------标注Bean的作用范围(单例或多个)
@Scope(“prototype”)或@Scope(“singleton”)
@PostConstruct------使用在方法上标注该方法是Bean的初始化方法(init-method)
@PostDestroy--------使用在方法上标注该方法是Bean的销毁方法(destroy-method)
Spring新注解:使用原始注解不能全部替代XML配置文件,还需要使用新注解进行配置替代,例如:
非自定义的Bean的配置:<bean>
加载properties文件的配置:<context:property-placeholder>
组件扫描的配置:<context:compponent-scan>
引入其他文件:<import>
@Configuration-----------用于指定当前类是一个Spring配置类,当创建容器时会从该类加载注解
@Configuration
public class SpringConfiguration {
}
代表核心配置类,管理其他子配置类。
创建ApplicationContext对象:
ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class)
@Import-------------------用于导入其他配置类
@Import({Configuration_1.class,Configuration_2.class,…})
导入核心配置类需要的分配置类,可存储数组对象
@ComponentScan-------用于指定Spring在初始化容器时要扫描的包
@ComponentScan(“com.xxx”)
参数为basepackage
@Bean---------------------使用在方法上,标注将该方法的返回值存储到Spring容器中
@Bean(“dataSource”)
返回id=dataSource的Bean,同时可以获取当前方法中set()中的属性值作为properties
@PropertySource--------用于加载properties文件中的配置