SpringIOC注解方式实现
maven所需依赖
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-context</ artifactId>
< version> 5.2.3.RELEASE</ version>
</ dependency>
< dependency>
< groupId> aspectj</ groupId>
< artifactId> aspectjweaver</ artifactId>
< version> 1.5.4</ version>
</ dependency>
applicationContext.xml文件配置
<?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"
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.xsd">
< context: annotation-config/>
< context: component-scan base-package = " my.xzb.pojo" />
</ beans>
环境准备
@Component
@Scope ( )
public class User {
@Value ( "你的名字是:红红" )
private String userName;
public void setUserName ( String userName) {
this . userName = userName;
}
public String getUserName ( ) {
return userName;
}
@Override
public String toString ( ) {
return "User{" +
"userName='" + userName + '\'' +
'}' ;
}
public User ( ) {
}
public User ( String userName) {
this . userName = userName;
}
}
public class Test {
public static void main ( String[ ] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext ( "beans.xml" ) ;
User user = ac. getBean ( "user" , User. class ) ;
System. out. println ( user) ;
}
}
注意:
@Autowired :自动装配通过类型。名字如果Autowired不能唯一 自动装配上属性,则需通过@Qualifier(value=" xxx") @Nullable :字段标记 了这个注解,说明这个字段可以为nu1l; @Resource : 自动装配通过名字。类型。 @Component :组件,放在类上,说明这个类被Spring管理了,就是bean! @Component 衍生注解用于不同层级 但功能相同(放在类上,说明这个类被Spring管理了,就是bean) dao > @Repository service > @Service controller > @Controller @Scope() :用于指定此bean的作用域 @Value(“你的名字是:红红”) :此注解可用于属性上,或set方法上 用于给属性赋值 两种方式对比: xml:配置繁琐,但理解容易且万能,维护简单… 注解:配置简单但维护难…