Spring学习笔记3
使用注解开发:
@Component 组件开发相当于
@Value(“xxx”)可以对属性进行赋值
package pojo;import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//等价于<bean id="user" class="pojo.User"/>
@Component
public class User {@Value("jack1")public String name;
}
@Component有几个衍生注解我们在web开发中,会按照MVC三层架构分层
dao @Repository
service @Service
controller@Controller
这四个注解功能是一样的,都代表将某个类注册到Spring中,装配Bean
总结:
xml与注解
xml更加万能,适用于任何场合,维护方便
注解不是自己的类使用不了,维护相对复杂
xml和注解最佳实践:
xml用来管理bean
注解只负责完成属性的注入
我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持
<context:component-scan base-package="pojo"/>
<context:annotation-config/>
使用Java的方式配置Spring
实体类
package pojo;import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;@Component
public class User {private String name;public String getName() {return name;}@Value("tom")public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "User{" +"name='" + name + '\'' +'}';}
}
配置类
package config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import pojo.User;
//类似于beans.xml,本身也是组件@Configuration
@ComponentScan("pojo")
public class MyConfig {//相当与之前的bean标签//方法名相当于id属性//返回值相当于class属性@Beanpublic User getUser(){return new User();//返回要注入bean的对象}
}
测试
import config.MyConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import pojo.User;public class MyTest {public static void main(String[] args) {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);User getUser = (User)context.getBean("getUser");System.out.println(getUser.getName());}
}
AOP
角色分析
抽象角色:一般会使用接口或抽象类来解决
真实角色:被代理的角色
代理角色:代理真实的角色,一般添加一些附属操作
客户:访问代理角色的人
代码步骤:1.接口
package demo01;public interface Rent {public void rent();
}
2.真实角色:
package demo01;public class Host implements Rent {public void rent() {System.out.println("房东租房");}}
3.代理角色
package demo01;public class Proxy implements Rent {private Host host;public Proxy() {}public Proxy(Host host) {this.host = host;}public void seeHouse(){System.out.println("look");}public void rent() {seeHouse();host.rent();}
}
4.客户访问
package demo01;public class Client {public static void main(String[] args) {Host host = new Host();Proxy proxy = new Proxy(host);proxy.rent();}
}
代理模式的好处:
1.可以使真实的角色操作更加纯粹,不用关注一些公共业务
2.实现业务分工
3.公共业务发生扩展时,方便集中管理