Spring常用配置及注解说明

pom.xml配置导入jar包:

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
    </dependencies>

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"
       xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
	<!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.liu"/>
    <!--注解驱动-->
    <context:annotation-config/>

</beans>

注解说明:

@Autowired:自动装配通过类型,名字,放在属性上

如果Autowired不能唯一自动装配属性,则需要通过@Qualifier(value=“”)

@Resource:自动装配通过名字,类型

@Nullable:说明此字段可以为null

@Component:组件,放在类上,说明这个类被spring管理了,无需在applicationContext.xml文件里配置bean

相当于

在beans.xml下要扫描包

<context:component-scan base-package="com.liu"/>

通过new ClassPathXmlApplicationContext()获取上下文容器

@Value(“liuxiang”)
相当于

dao【@Repository】:将类注册到spring中

service【@Service】:将类注册到spring中

controller【@Controller】

@Scope(“singleton”):单例模式

@Scope(“protoType”):原型模式

@Configuration:本身也是一个bean,会被spring托管注册到容器中去,本质上一个@Compnent,代表配置类,和applicationConfig.xml一样

所以可以用注解扫描包:

@ComponentScan("com.liu.pojo")

@Bean下的方法名就是bean对象,相当于id属性,返回值是class属性

通过AnnotationConfigApplicationContext获取上下文容器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值