spring注解功能小记

想要引用注解功能,首先需要在applicationContext.xml中进行配置,beans头如下:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

然后再在下面添加一行代码:

<context:component-scan base-package="cn.com.test,cn.com.mv"></context:component-scan> 

这其中base-package中指向的包就是可以使用注释的包,可以向这段代码中一样添加多个包,对于添加在这里的包,spring容器启动时会自动从中寻找添加了注解的类,然后注入,进行对象的初始化。

寻找的过程中寻找的注解是@Repository、@Service和@Controller,分别对应原来的DAO类、service类以及action类,非常的清晰。

添加了注解的类,诸如

@Service(value="userService")
public class UserService {

    @Autowired
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

就好比是在xml文件中添加了如下两行:

<bean id="userService" class="cn.com....UserService" >
    <property name="user" ref="user"></property>
<bean>

这样就实现了注解注入。

注入是spring容器中xml就可以实现的功能,而注解实现注入更多的则是为了简化xml文件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring注解功能是指在Spring框架中使用注解来配置和管理应用程序的功能。通过使用注解,可以将配置信息直接写在Java类中,而不需要使用XML文件。在Spring中,有几个常用的注解用于实现不同的功能。 @Configuration注解用于标记一个类为配置类,替代了传统的XML配置文件。被@Configuration注解修饰的类会被Spring容器扫描并将其作为配置信息加载到容器中。 @Bean注解用于标记一个方法为Bean的定义方法。被@Bean注解修饰的方法会被Spring容器调用,并将其返回的对象作为Bean存入容器中。 @Import注解用于导入其他配置类。通过@Import注解,可以将其他配置类中定义的Bean导入到当前配置类中。 @DependsOn注解用于指定Bean之间的依赖关系。通过@DependsOn注解,可以确保在创建Bean时,其所依赖的Bean已经被创建。 @PropertySource注解用于指定属性文件的位置。通过@PropertySource注解,可以将属性文件中的属性值注入到Bean中。 除了上述常用的注解外,Spring还提供了许多其他的注解,用于实现不同的功能,如@Component、@Autowired、@Qualifier等。 总之,Spring注解功能可以简化配置文件的编写,提高开发效率,并且使得配置更加灵活和易于维护。 #### 引用[.reference_title] - *1* *2* *3* [Spring注解详解](https://blog.csdn.net/gelingxian/article/details/123484052)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值