城市直播房产教育博客汽车
投稿投诉
汽车报价
买车新车
博客专栏
专题精品
教育留学
高考读书
房产家居
彩票视频
直播黑猫
投资微博
城市上海
政务旅游

Spring注解编程

3月3日 喵小咪投稿
  Spring多文件配置处理
  通配符方式非web环境ApplicationContextctxnewClassPathXmlApplicationContext(applicationContext。xml);web环境contextparamparamnamecontextConfigLocationparamnameparamvalueclasspath:applicationContext。xmlparamvaluecontextparamimport标签applicationContext。xml整合其他配置内容importresourceapplicationContextdao。xmlimportresourceapplicationContextservice。xml。。。非web环境ApplicationContextctxnewClassPathXmlApplicationContext(applicationContext。xml);web环境contextparamparamnamecontextConfigLocationparamnameparamvalueclasspath:applicationContext。xmlparamvaluecontextparam接口的契约性
  注解的契约性
  Spring的基础注解
  在Spring框架应用注解时,如果对注解配置的内容不满意,可以通过Spring配置文件进行覆盖。对象创建相关注解
  》》》搭建开发环境!让Spring框架在设置包及其子包中扫描对应的注解,使其生效context:componentscanbasepackagecom。demo
  》》》对象相关注解
  1)Component:替换原有Spring配置文件中bean标签显示指定工厂创建对象的id值:Component(u);
  Spring配置文件覆盖注解配置内容:
  2)Component的衍生注解以下三种注解能更加准确的表达一个类型的作用
  Repository》XXXDAO
  Service》XXXService
  Controller
  注意:本质上这些衍生注解就是Component,作用、细节、用法完全一致
  Spring整合MyBatis开发过程中,不使用Repository、Component,原因是DAO的对象是动态代理创建的
  3)Scope:控制简单对象创建次数
  注意:不添加ScopeSpring提供默认值singleton
  4)Lazy:延迟创建单实例对象
  注意:使用Lazy注解后,Spring使用这个对象的时候,才会进行对象的创建
  5)生命周期相关注解
  注入相关注解
  》》》Autowired用户自定义类型
  Autowired基于类型进行注入:注入对象的类型,必须与目标成员变量类型相同或者是其子类(实现类)推荐
  AutowiredQualifier基于名字进行注入
  Autowired放置位置
  a)放置在对应成员变量的set方法上
  b)放置在成员变量之上,Spring通过反射直接对成员变量进行注入(赋值)推荐
  JavaEE规范中类似功能的注解
  JSR250Resource(nameuserDAOImpl)基于名字进行注入
  Autowired()
  Qualifier(userDAOImpl)
  注意:如果在应用Resource注解时,名字没有配对成功,那么会继续按照类型进行注入
  JSR330Inject作用Autowired完全一致基于类型进行注入EJB3。0dependencygroupIdjavax。injectgroupIdjavax。injectartifactIdversion1versiondependency
  》》》JDK类型
  1)Value注解不能应用在静态成员变量上,否则赋值(注入)失败
  该注解Properties这种方式,不能注入集合类型,YMALYML配置方式替代
  2)PropertySource
  注解扫描当前包及其子包context:componentscanbasepackagecom。demo
  》》》排除方式
  》》》包含方式
  注解开发的思考
  》》》配置互通
  》》》注解和配置文件使用的条件程序员自己开发的类型,可以加入对应的注解,进行对象创建。
  非程序员开发的类型,需要配置文件(bean标签来完成)进行配置。(如:SqlSessionFactoryBean、MapperScannerConfigure)SSM半注解DAO(SpringMyBatis)
  Service
  ControllerSpring的高级注解配置Bean
  Configuration实际上是Component的衍生注解
  》》》配置日志
  基于注解开发,不能集成log4j,发现没有日志打印
  基于注解开发,集成的是logback!引入logback相关依赖dependencygroupIdorg。slf4jgroupIdslf4japiartifactIdversion1。7。25versiondependencydependencygroupIdorg。slf4jgroupIdjcloverslf4jartifactIdversion1。7。25versiondependencydependencygroupIdch。qos。logbackgroupIdlogbackclassicartifactIdversion1。2。3versiondependencydependencygroupIdch。qos。logbackgroupIdlogbackcoreartifactIdversion1。2。3versiondependencydependencygroupIdorg。logbackextensionsgroupIdlogbackextspringartifactIdversion0。1。4versiondependency!resources目录下创建logback。xml配置文件?xmlversion1。0encodingUTF8?configurationencoder!格式化输出:d:日期thread:线程名5level:级别从左显示5个字符宽度msg:ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a消息n:换行符patternd{yyyyMMddHH:mm:ss。SSS}〔thread〕5levellogger{50}msgnpatternencoderappenderrootlevelDEBUGrootconfigurationAnnotationConfigApplicationContext
  Bean注解
  等同于XML配置文件中bean标签
  》》》对象的创建简单对象:直接通过new方式创建的对象
  复杂对象:不能通过new方式创建的对象(如:Connection,SqlSessionFactory)
  packagecom。importcom。demo。bean。Uimportorg。springframework。context。annotation。Bimportorg。springframework。context。annotation。Cimportjava。sql。Cimportjava。sql。DriverMimportjava。sql。SQLEConfigurationpublicclassAppConfig{简单对象returnBeanpublicUseruser(){returnnewUser();}复杂对象(推荐使用)Connection不能直接通过new创建returnBeanpublicConnectionconn(){Ctry{Class。forName(com。mysql。cj。jdbc。Driver);connDriverManager。getConnection(jdbc:mysql:192。168。XXX。222:3306ssmdb?useSSLfalse,root,root);}catch(ClassNotFoundExceptione){e。printStackTrace();}catch(SQLExceptionthrowables){throwables。printStackTrace();}}}packagecom。demo。importorg。springframework。beans。factory。FactoryBimportjava。sql。Cimportjava。sql。DriverMpublicclassConnectionFactoryBeanimplementsFactoryBeanConnection{OverridepublicConnectiongetObject()throwsException{Class。forName(com。mysql。cj。jdbc。Driver);ConnectionconnDriverManager。getConnection(jdbc:mysql:192。168。XXX。222:3306ssmdb?useSSLfalse,root,root);}OverridepublicC?getObjectType(){returnConnection。}OverridepublicbooleanisSingleton(){}}遗留系统使用该方式创建很少自己写ConnectionFactoryBean,来创建复杂对象returnBeanpublicConnectionconn(){Ctry{ConnectionFactoryBeanfactoryBeannewConnectionFactoryBean();connfactoryBean。getObject();}catch(Exceptione){e。printStackTrace();}}
  》》》自定义id值
  Bean(id)
  》》》控制对象创建次数Bean
  Scope(singletonprototype)默认值singletonBean注解的注入
  》》》用户自定义注入packagecom。importcom。demo。injection。UserDAO;importcom。demo。injection。UserDAOIimportcom。demo。injection。UserSimportcom。demo。injection。UserServiceIimportorg。springframework。context。annotation。Bimportorg。springframework。context。annotation。CConfigurationpublicclassAppConfig{BeanpublicUserDAOuserDAO(){returnnewUserDAOImpl();}BeanpublicUserServiceuserService(UserDAOuserDAO){UserServiceImpluserServicenewUserServiceImpl();userService。setUserDAO(userDAO);returnuserS}}packagecom。importcom。demo。injection。UserDAO;importcom。demo。injection。UserDAOIimportcom。demo。injection。UserSimportcom。demo。injection。UserServiceIimportorg。springframework。context。annotation。Bimportorg。springframework。context。annotation。CConfigurationpublicclassAppConfig{BeanpublicUserDAOuserDAO(){returnnewUserDAOImpl();}简化写法(没有把userDAO作为形参传入)BeanpublicUserServiceuserService(){UserServiceImpluserServicenewUserServiceImpl();userService。setUserDAO(userDAO());returnuserS}}
  》》》JDK类型注入BeanpublicCustomercustomer(){CustomercustomernewCustomer();硬代码耦合customer。setId(1);customer。setName(zhangsan);}packagecom。importcom。demo。bean。Cimportorg。springframework。beans。factory。annotation。Vimportorg。springframework。context。annotation。Bimportorg。springframework。context。annotation。Cimportorg。springframework。context。annotation。PropertyS读取配置文件init。properties,解决耦合问题ConfigurationPropertySource(classpath:init。properties)publicclassAppConfig{Value({id})privateIValue({name})privateSBeanpublicCustomercustomer(){CustomercustomernewCustomer();customer。setId(id);customer。setName(name);}}ComponentScan注解ComponentScan等同于XML配置文件中的标签
  目的:扫描注解(如:Component、Value、Autowired。。。)
  》》》排除、包含的使用
  1)排除
  2)包含
  Spring多种配置方式
  》》》配置优先级配置文件bean标签BeanComponent及其衍生注解
  优先级高的配置覆盖优先级低的配置
  配置的优先级能解决耦合问题
  ApplicationContextctxnewAnnotationConfigApplicationContext(AppConfig4。class,AppConfig5。class);ApplicationContextctxnewAnnotationConfigApplicationContext(com。demo。config);多个配置信息
  》》》多配置信息整合
  多个配置Bean的整合
  1)basepackage进行多个配置Bean的整合
  2)Import
  1。可以创建对象
  2。多配置bean的整合
  3)指定多个配置Bean的Class对象ApplicationContextctxnewAnnotationConfigApplicationContext(AppConfig1。class,AppConfig2。class,。。。);
  配置Bean与Component相关注解的整合
  配置Bean与SpringXML配置文件的整合
  跨配置的注入
  配置Bean底层实现原理
  Spring在配置Bean中加入了Configuration注解后,底层就会通过CGlib的代理方式,来进行对象相关的配置、处理四维一体的开发思想
  基于schema
  基于特定功能注解推荐
  基于原始beanbeannameclassorg。springframework。context。support。PropertySourcesPlaceholderConfigurerpropertynamelocationvalueclasspath:init。propertiesbean
  基于Bean注解推荐packagecom。importorg。springframework。context。annotation。;importorg。springframework。context。support。PropertySourcesPlaceholderCimportorg。springframework。core。io。ClassPathRConfigurationComponentScan(basePackagescom。demo)publicclassAppConfig{BeanpublicPropertySourcesPlaceholderConfigurerconfigurer(){PropertySourcesPlaceholderConfigurerconfigurernewPropertySourcesPlaceholderConfigurer();configurer。setLocation(newClassPathResource(init。properties));}}纯注解版AOP编程
  packagecom。demo。publicinterfaceUserService{voidregister();voidlogin();}packagecom。demo。importorg。springframework。stereotype。SServicepublicclassUserServiceImplimplementsUserService{Overridepublicvoidregister(){System。out。println(UserServiceImpl。register);}Overridepublicvoidlogin(){System。out。println(UserServiceImpl。login);}}packagecom。demo。importorg。aspectj。lang。ProceedingJoinPimportorg。aspectj。lang。annotation。Aimportorg。aspectj。lang。annotation。Aimportorg。aspectj。lang。annotation。Pimportorg。springframework。stereotype。CAspectComponentpublicclassMyAspect{Pointcut(execution(com。demo。aop。。。(。。)))publicvoidpointCut(){}Around(pointCut())publicObjectarroud(ProceedingJoinPointjoinPoint)throwsThrowable{System。out。println(Log);ObjectproceedjoinPoint。proceed();}}packagecom。demo。importorg。springframework。context。annotation。ComponentSimportorg。springframework。context。annotation。Cimportorg。springframework。context。annotation。EnableAspectJAutoPConfigurationComponentScan(basePackagescom。demo。aop)EnableAspectJAutoProxypublicclassAOPConfig{}
  》》》注解AOP细节分析SpringAOP代理默认:JDK
  SpringBootAOP代理默认:CGlib
  纯注解版SpringMyBatis整合基础配置(配置Bean)
  packagecom。demo。importcom。alibaba。druid。pool。DruidDataSimportorg。mybatis。spring。SqlSessionFactoryBimportorg。mybatis。spring。annotation。MapperSimportorg。springframework。context。annotation。Bimportorg。springframework。context。annotation。ComponentSimportorg。springframework。context。annotation。Cimportorg。springframework。core。io。Rimportorg。springframework。core。io。support。PathMatchingResourcePatternRimportorg。springframework。core。io。support。ResourcePatternRimportjavax。sql。DataSimportjava。io。IOEConfigurationComponentScan(basePackagescom。demo。mybatis)MapperScan(basePackagescom。demo。mybatis)publicclassMyBatisAutoConfiguration{BeanpublicDataSourcedataSource(){DruidDataSourcedataSourcenewDruidDataSource();dataSource。setDriverClassName(com。mysql。cj。jdbc。Driver);dataSource。setUrl(jdbc:mysql:192。168。30。222:3306ssmdb);dataSource。setUsername(root);dataSource。setPassword(root);returndataS}BeanpublicSqlSessionFactoryBeansqlSessionFactoryBean(DataSourcedataSource){SqlSessionFactoryBeansqlSessionFactoryBeannewSqlSessionFactoryBean();sqlSessionFactoryBean。setDataSource(dataSource);sqlSessionFactoryBean。setTypeAliasesPackage(com。demo。mybatis);sqlSessionFactoryBean。setMapperLocations(newClassPathResource(UserDAOMapper。xml));try{ResourcePatternResolverresolvernewPathMatchingResourcePatternResolver();Resource〔〕resourcesresolver。getResources(comdemomapperMapper。xml);sqlSessionFactoryBean。setMapperLocations(resources);}catch(IOExceptione){e。printStackTrace();}returnsqlSessionFactoryB}}配置Bean耦合问题mybatis。driverClassNamecom。mysql。cj。jdbc。Drivermybatis。urljdbc:mysql:192。168。XXX。222:3306ssmdbmybatis。usernamerootmybatis。passwordrootmybatis。typeAliasesPackagescom。demo。mybatismybatis。mapperLocationscomdemomapperMapper。xmlpackagecom。demo。importlombok。Dimportorg。springframework。beans。factory。annotation。Vimportorg。springframework。context。annotation。PropertySimportorg。springframework。stereotype。CDataComponentPropertySource(classpath:mybatis。properties)publicclassMybatisProperties{Value({mybatis。driverClassName})privateStringdriverClassNValue({mybatis。url})privateSValue({mybatis。username})privateSValue({mybatis。password})privateSValue({mybatis。typeAliasesPackages})privateStringtypeAliasesPValue({mybatis。mapperLocations})privateStringmapperL}packagecom。demo。importcom。alibaba。druid。pool。DruidDataSimportorg。mybatis。spring。SqlSessionFactoryBimportorg。mybatis。spring。annotation。MapperSimportorg。springframework。beans。factory。annotation。Aimportorg。springframework。context。annotation。Bimportorg。springframework。context。annotation。ComponentSimportorg。springframework。context。annotation。Cimportorg。springframework。core。io。Rimportorg。springframework。core。io。support。PathMatchingResourcePatternRimportorg。springframework。core。io。support。ResourcePatternRimportjavax。sql。DataSimportjava。io。IOEConfigurationComponentScan(basePackagescom。demo。mybatis)MapperScan(basePackagescom。demo。mybatis)publicclassMyBatisAutoConfiguration{AutowiredprivateMybatisPropertiesmybatisPBeanpublicDataSourcedataSource(){DruidDataSourcedataSourcenewDruidDataSource();dataSource。setDriverClassName(mybatisProperties。getDriverClassName());dataSource。setUrl(mybatisProperties。getUrl());dataSource。setUsername(mybatisProperties。getUsername());dataSource。setPassword(mybatisProperties。getPassword());returndataS}BeanpublicSqlSessionFactoryBeansqlSessionFactoryBean(DataSourcedataSource){SqlSessionFactoryBeansqlSessionFactoryBeannewSqlSessionFactoryBean();sqlSessionFactoryBean。setDataSource(dataSource);sqlSessionFactoryBean。setTypeAliasesPackage(mybatisProperties。getTypeAliasesPackages());sqlSessionFactoryBean。setMapperLocations(newClassPathResource(UserDAOMapper。xml));try{ResourcePatternResolverresolvernewPathMatchingResourcePatternResolver();Resource〔〕resourcesresolver。getResources(mybatisProperties。getMapperLocations());sqlSessionFactoryBean。setMapperLocations(resources);}catch(IOExceptione){e。printStackTrace();}returnsqlSessionFactoryB}}纯注解版事务编程
  packagecom。demo。publicinterfaceUserService{voidregister(Useruser);}packagecom。demo。importlombok。Dimportorg。springframework。beans。factory。annotation。Aimportorg。springframework。stereotype。Simportorg。springframework。transaction。annotation。TDataServiceTransactionalpublicclassUserServiceImplimplementsUserService{AutowiredprivateUserDAOuserDAO;Overridepublicvoidregister(Useruser){userDAO。save(user);}}packagecom。demo。importorg。springframework。beans。factory。annotation。Aimportorg。springframework。context。annotation。Bimportorg。springframework。context。annotation。Cimportorg。springframework。jdbc。datasource。DataSourceTransactionMimportorg。springframework。transaction。annotation。EnableTransactionMimportjavax。sql。DataSConfigurationEnableTransactionManagementpublicclassTransactionAutoConfiguration{AutowiredprivateDataSourcedataSBeanpublicDataSourceTransactionManagerdataSourceTransactionManager(){DataSourceTransactionManagerdataSourceTransactionManagernewDataSourceTransactionManager();dataSourceTransactionManager。setDataSource(dataSource);returndataSourceTransactionM}}Spring中YAMLYML使用
  YML语法
  Spring与YML集成
  dependencygroupIdorg。yamlgroupIdsnakeyamlartifactIdversion2。0versiondependency
  》》》init。ymlaccount:name:zhangsanpassword:rootpackagecom。demo。importlombok。Dimportorg。springframework。beans。factory。annotation。Vimportorg。springframework。stereotype。CDataComponentpublicclassAccount{Value({account。name)privateSValue({account。password})privateS}packagecom。demo。importorg。springframework。beans。factory。config。YamlPropertiesFactoryBimportorg。springframework。context。annotation。Bimportorg。springframework。context。annotation。ComponentSimportorg。springframework。context。annotation。Cimportorg。springframework。context。support。PropertySourcesPlaceholderCimportorg。springframework。core。io。ClassPathRimportjava。util。PConfigurationComponentScan(basePackagescom。demo。yml)publicclassYmlAutoConfiguration{BeanpublicPropertySourcesPlaceholderConfigurerconfigurer(){YamlPropertiesFactoryBeanyamlPropertiesFactoryBeannewYamlPropertiesFactoryBean();yamlPropertiesFactoryBean。setResources(newClassPathResource(init。yml));PropertiespropertiesyamlPropertiesFactoryBean。getObject();PropertySourcesPlaceholderConfigurerconfigurernewPropertySourcesPlaceholderConfigurer();configurer。setProperties(properties);}}Spring与YML集成问题
  》》》init。ymlaccount:name:zhangsanpassword:rootlist:111,222packagecom。demo。importlombok。Dimportorg。springframework。beans。factory。annotation。Vimportorg。springframework。stereotype。Cimportjava。util。LDataComponentpublicclassAccount{Value({account。name)privateSValue({account。password})privateSValue({{list}。split(,)})privateListS}
投诉 评论 转载

济宁能源产业链供应链协同配套对接会成功举办3月23日,以聚力强链协同携手合作共赢为主题的2023年产业链供应链协同配套济宁能源发展集团专场对接会在济宁高新区成功举办。会议吸引了来自济宁本地的110家企业现场观摩交流。……他说,只有穷人才修行我的一个亲戚,在一次家族聚餐的饭后,他说了句:只有穷人才修行!我当时听见这句话的时候没有任何反应,但后来细想,释迦摩尼佛修行是为了渡众生!释迦摩尼佛是古印度的王子,……BatteryGuruforAndroid电池大师可以更好的检测手机电池相关情况的一个应用,BatteryGuru是个汉化版本,解锁了付费功能,所有功能都能免费用,还能显示电池使用情况信息,测量电池容量,延长电池寿命,需要的自……加西亚莱昂23744新世界纪录中国选手刘虹创下了亚洲纪录加西亚莱昂(22年俄勒冈世界田径)世界陆联(WA)竞走巡回赛金牌杜丁站50(斯洛伐克)在3月25日举行的女子35公里竞走比赛中,秘鲁选手金贝尔利加西亚莱昂以2小时37分4……C罗用出色表现再破纪录头条创作挑战赛克里斯蒂亚诺罗纳尔多(CristianoRonaldo)很快就将世界杯的失望抛在脑后。作为葡萄牙国家队的首发球员,罗纳尔多成为男子国际足球比赛中出场次数最多……强!梦百合国手大咖纷纷驻足,10年小将竟拿捏LG世冠!爆冷将轰动!国手大咖纷纷驻足观看,10年小将竟然拿捏LG世冠,爆冷即将产生!24日,梦百合杯预选大战第3轮,中国98年LG世界冠军谢尔豪九段与10后棋手、小将田沐沐遭遇,本盘激战并没……甘肃陇南鲟鱼零等待出口争鲜机图为产自甘肃陇南市文县的冷水鲟鱼。(资料图)高志鑫摄中新网兰州3月23日电(闫姣刘雅冰)设零等待绿色通道、建724小时预约通关机制、助出口货物争鲜机连日来,产自甘肃陇南市……不管你生过几胎,都别超这个年龄再生育,有这2大不同现在大多数年轻人不想生孩子,因为孩子到来要考虑许多问题,除了给予最好的家庭环境,还考虑到后续学业,工作,一想到这些就让人头疼。但传宗接代是自古以来适龄男女的任务,如果到了一定年……有剧毒!一地已出现,看到立即远离去海边欣赏美景是不少人的度假首选,但需要注意的是,大海很美,却也险象环生。如果在海边看到这种像塑料袋又像气球的生物,要立即远离、千万别碰!有剧毒!……爱家无需理由爱家无需理由山一大二附院秋枫李艳丽家,是亲人们相互依赖、相互照顾、相互安慰、相互支持,需共同奋斗、共同营造、共同建设、共同维护的综合体。俗话说得好:子不嫌母丑……Spring注解编程Spring多文件配置处理通配符方式非web环境ApplicationContextctxnewClassPathXmlApplicationContext(applic……情歌王子张信哲,他的故事远比你想象的还要精彩在整个华语歌坛里,能够担得起情歌王子这个称号的,只有张信哲一个人。我想,你一定听过情歌王子的《信仰》《爱如潮水》《过火》等等,一个在歌坛红极一时的人,实力碾压张学友,他的歌曲成……
宁波破4000亿,苏州升至第二!半年度出口贸易十强出炉杰克奥特曼扮演者团时朗去世,网友一定是回到M78星云了范志毅25岁女儿为富二代男友庆生,穿着清凉打扮成熟,国籍没想自进化大孔的超分子水凝胶培养多细胞球扎堆排队!临近春节,过年三件套火了投融资周报最新市值超80亿元,计量仪表商真兰仪表创业板上市消化道出血有什么表现?如何预防?早春乡村旅游热度涨400,广州乡村游订单量10倍增长如果在昆明待一天,我要有一种叫云南的生活美国终于重新登月了!中国人对此怎么看?学龄前儿童的生理特点与营养需求上海久事男篮鲨回主场,遗憾不敌吉林男篮错过主场首胜

友情链接:中准网聚热点快百科快传网快生活快软网快好知文好找江西南阳嘉兴昆明铜陵滨州广东西昌常德梅州兰州阳江运城金华广西萍乡大理重庆诸暨泉州安庆南充武汉辽宁