注解的学习

本文介绍了如何在Spring框架中利用注解如@Autowired、@Qualifier进行组件自动装配,以及如何通过@Service、@Controller等注解创建并配置服务。重点讲解了基于注解的完全开发流程和配置类的使用,适合理解Spring DI的开发者阅读。
摘要由CSDN通过智能技术生成

autowire注入

格式

<bean id="" value="" autowire="byName"(or byType)></bean>

注解扫描:

<context:component-scan base-package="要扫描的包" > </context:component-scan>
//扫描该包中的所有的类
<context:component-scan base-package="要扫描的包" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.sterrotype.Controller"/> 
</context:component-scan>
//use-default-filters="false"作用不扫描该包里的所有类,
//<context:include-filter type="annotation" expression="org.springframework.sterrotype.Controller">只扫描带Controller的类

<context:component-scan base-package="要扫描的包" > 
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
//context:exclude-filter 不扫描带Controller注解的类

@Component

@Service

@Controller

@Repository

@Service(value="userService")

注解使用格式如上;相当于<bean id = "userService" class="">

在value属性值可以不写,则默认是类的名称首字母小写。

以上四个注解功能相同。

基于注解方式实现属性注入:

@Autowired:根据类型进行自动装配

@Qualifier:根据属性名称进行注入,与Autowired配对使用

@Resource:可以根据类型注入,可以根据名称注入 

@Value:注入普通类型属性

以上四种注解写在引入的属性之上,方法之下如:

@Service
public class UserService{
@Value(value = "abc" )
private String name
@Autowire
@Qualifier(value = "...")//名称与UserDao中设置的id相同
private UserDao userDao;
}

完全注解开发:

(1).创建配置类文件 

@Configuration//作为配置类,代替xml文件

@ComponentScan(basePackages = {"com.ithimes"});

public class SpringConfig{

}




@Test
public void testService2(){
    
    AplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
//配置类变化
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值